Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sany2k8/0bc46b504b4cdde8a32bfbcf55a3f5bd to your computer and use it in GitHub Desktop.
Save sany2k8/0bc46b504b4cdde8a32bfbcf55a3f5bd to your computer and use it in GitHub Desktop.
Pydantic Phone Number Field
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