Last active
August 1, 2024 09:47
-
-
Save iRhonin/b7d2467fecdc43717beacf0d8376ae6c to your computer and use it in GitHub Desktop.
Pydantic Phone Number Field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import phonenumbers | |
from pydantic.validators import strict_str_validator | |
class PhoneNumber(str): | |
"""Phone Number Pydantic type, using google's phonenumbers""" | |
@classmethod | |
def __get_validators__(cls): | |
yield strict_str_validator | |
yield cls.validate | |
@classmethod | |
def validate(cls, v: str): | |
# Remove spaces | |
v = v.strip().replace(' ', '') | |
try: | |
pn = phonenumbers.parse(v) | |
except phonenumbers.phonenumberutil.NumberParseException: | |
raise ValueError('invalid phone number format') | |
return cls(phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.E164)) | |
# Usage | |
from pydantic import BaseModel, ValidationError | |
class PhoneNumberModel(BaseModel): | |
phone_number: PhoneNumber | |
print(PhoneNumberModel(phone_number='+123456789')) | |
#> phone_number='+123456789' | |
try: | |
PhoneNumberModel(phone_number='123456789') | |
except ValidationError as e: | |
print(str(e)) | |
""" | |
1 validation error for PhoneNumberModel | |
phone_number | |
invalid phone number format (type=value_error) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use the bultin PhoneNumber field from Pydantic: https://docs.pydantic.dev/latest/api/pydantic_extra_types_phone_numbers/#pydantic_extra_types.phone_numbers