Files
2026-09-22 00:50:30 +05:00

30 lines
891 B
Python

"""Maldives mobile number normalisation.
Everything past the serializer layer deals in E.164 (`+960XXXXXXX`) so a
number is stored and looked up exactly one way.
"""
import re
from django.core.exceptions import ValidationError
COUNTRY_CODE = "960"
LOCAL_LENGTH = 7
# Maldives mobile prefixes are 7xx and 9xx.
LOCAL_RE = re.compile(r"^[79]\d{6}$")
def normalize_mobile(value: str) -> str:
"""Return `value` as +960XXXXXXX, or raise ValidationError."""
digits = re.sub(r"[\s()-]", "", str(value or "")).lstrip("+")
if digits.startswith("00" + COUNTRY_CODE):
digits = digits[len("00" + COUNTRY_CODE) :]
elif digits.startswith(COUNTRY_CODE) and len(digits) > LOCAL_LENGTH:
digits = digits[len(COUNTRY_CODE) :]
if not LOCAL_RE.match(digits):
raise ValidationError("Enter a valid Maldives mobile number.")
return f"+{COUNTRY_CODE}{digits}"