Skip to content

Instantly share code, notes, and snippets.

@iRhonin
Last active August 1, 2024 09:47
Show Gist options
  • Save iRhonin/b7d2467fecdc43717beacf0d8376ae6c to your computer and use it in GitHub Desktop.
Save iRhonin/b7d2467fecdc43717beacf0d8376ae6c 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)
"""
@iRhonin
Copy link
Author

iRhonin commented Aug 1, 2024

strict_str_validator is no longer a module of pydantic.validators

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment