Forked from iRhonin/pydantic_phone_number_field.py
Created
September 16, 2022 14:54
-
-
Save sany2k8/0bc46b504b4cdde8a32bfbcf55a3f5bd 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