pydantic / pydantic-extra-types

Extra Pydantic types.
MIT License
181 stars 48 forks source link

Feature: Add phone number validator #203

Closed mZbZ closed 1 month ago

mZbZ commented 1 month ago

Hi

This PR adds a new custom BeforeValidator annotation based phone number type instead of the concrete type that exists: PhoneNumberValidator

Args:
    default_region (str | None): The default region code to use when parsing phone numbers without an international prefix.
        If `None` (default), the region must be supplied in the phone number as an international prefix.
    number_format (str): The format of the phone number to return. See `phonenumbers.PhoneNumberFormat` for valid values.
    supported_regions (list[str]): The supported regions. If empty, all regions are supported (default).
Returns:
    str: The formatted phone number.

This provides be an option for more composable phone number types, e.g:

from phonenumbers import PhoneNumber
from pydantic_extra_types.phone_numbers import PhoneNumberValidator

# Supports any number supplied with an international code
AnyNumberType = Annotated[
    Union[str, PhoneNumber],
    PhoneNumberValidator()
]
# Supports only US phone numbers
USNumberType = Annotated[
    Union[str, PhoneNumber],
    PhoneNumberValidator(supported_regions=['US'], default_region='US')
]

class SomeModel(BaseModel):
    phone_number: AnyNumberType
    us_number: USNumberType
codecov[bot] commented 1 month ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 100.00%. Comparing base (e186814) to head (b3d12f7). Report is 42 commits behind head on main.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #203 +/- ## ========================================== Coverage 100.00% 100.00% ========================================== Files 11 17 +6 Lines 685 999 +314 Branches 169 244 +75 ========================================== + Hits 685 999 +314 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.