pydantic-extra-types icon indicating copy to clipboard operation
pydantic-extra-types copied to clipboard

How to set region-code or format-type for PhoneNumber?

Open nameer opened this issue 2 years ago • 3 comments

The documentation has no example to override the default-set region code or format.

I have also gone through stack overflow. The suggestions found there were not optimal.

One of the suggestions is as follows:

from pydantic import BaseModel
from pydantic_extra_types.phone_numbers import PhoneNumber

PhoneNumber.phone_format = 'E164' #'INTERNATIONAL', 'NATIONAL'

class User(BaseModel):
    name: str
    phone_number: PhoneNumber

But this will restrict the whole app to use a single format and region code. If I need another format in another place, this will be overridden.

What is the correct way of setting region code and format for a model?

nameer avatar Nov 16 '23 08:11 nameer

Yeah. I think we need to refactor the logic we have in place.

Kludex avatar Nov 16 '23 14:11 Kludex

I think a Field like behavior would be useful:

class User(BaseModel):
    name: str
    phone_number: PhoneNumber(phone_format="E164", ...)

Abdelgha-4 avatar Jun 18 '24 22:06 Abdelgha-4

The documentation has no example to override the default-set region code or format.

I have also gone through stack overflow. The suggestions found there were not optimal.

One of the suggestions is as follows:

from pydantic import BaseModel
from pydantic_extra_types.phone_numbers import PhoneNumber

PhoneNumber.phone_format = 'E164' #'INTERNATIONAL', 'NATIONAL'

class User(BaseModel):
    name: str
    phone_number: PhoneNumber

But this will restrict the whole app to use a single format and region code. If I need another format in another place, this will be overridden.

What is the correct way of setting region code and format for a model?

i was looking for an answer to this, and found a badly formatted example on this page. below is my personal spin on it, and it seems to work for me

from typing import Annotated, Union

from pydantic_extra_types.phone_numbers import PhoneNumber, PhoneNumberValidator

PhoneNumberType = Annotated[
    Union[str, PhoneNumber],
    PhoneNumberValidator(default_region="NG", number_format="E164"),
]

dodumosu avatar Dec 05 '24 13:12 dodumosu