Spaces:
Sleeping
Sleeping
| """ | |
| Phone Utilities - Phone number normalization and validation | |
| """ | |
| def normalize_kenyan_phone(phone: str) -> str: | |
| """ | |
| Normalize Kenyan phone number to +254XXX format. | |
| Handles formats: | |
| - +254712345678 (already normalized) | |
| - 254712345678 | |
| - 0712345678 | |
| - 712345678 | |
| Returns normalized +254XXXXXXXXX or original if invalid. | |
| """ | |
| if not phone: | |
| return phone | |
| # Remove spaces, dashes, parentheses, keep only digits and + | |
| phone = ''.join(c for c in str(phone) if c.isdigit() or c == '+') | |
| if not phone: | |
| return phone | |
| # Already normalized | |
| if phone.startswith('+254') and len(phone) == 13: | |
| return phone | |
| # Remove leading +254 | |
| if phone.startswith('+254'): | |
| phone = phone[4:] | |
| # Remove leading 254 | |
| if phone.startswith('254'): | |
| phone = phone[3:] | |
| # Remove leading 0 | |
| if phone.startswith('0'): | |
| phone = phone[1:] | |
| # Should now have 9 digits (7XXXXXXXX or 1XXXXXXXX) | |
| if len(phone) == 9 and phone[0] in ['7', '1']: | |
| return f'+254{phone}' | |
| # Invalid format - return original input (don't break) | |
| return phone | |