import re from django.utils.translation import gettext as _ def normalize_phone_number(raw_phone: str) -> str: if not raw_phone: raise ValueError(_("Phone number is required")) phone = re.sub(r"[\s\-\(\)]", "", raw_phone) if phone.startswith("00"): phone = "+" + phone[2:] if phone.startswith("+"): digits = phone[1:] if not digits.isdigit() or not (8 <= len(digits) <= 15): raise ValueError(_("Invalid phone number format")) return "+" + digits digits = re.sub(r"\D", "", phone) if digits.startswith("0") and len(digits) == 10 and digits[1] == "5": return "+966" + digits[1:] if digits.startswith("5") and len(digits) == 9: return "+966" + digits raise ValueError(_("Phone number must be in E.164 format or a valid Saudi mobile"))