Skip to content

Commit

Permalink
Added __get_pydantic_json_schema__ method with format='tel' (#106)
Browse files Browse the repository at this point in the history
* Added __get_pydantic_json_schema__ method with format='tel'

* Formatted.

* Added 'test_json_schema'

* Reformatted.

* Change format value from 'tel' to 'phone'

* Update pydantic_extra_types/phone_numbers.py

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>

---------

Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
  • Loading branch information
hasansezertasan and Kludex authored Nov 11, 2023
1 parent a973b79 commit 843b753
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
10 changes: 9 additions & 1 deletion pydantic_extra_types/phone_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from typing import Any, Callable, ClassVar, Generator

from pydantic import GetCoreSchemaHandler
from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler
from pydantic_core import PydanticCustomError, core_schema

try:
Expand Down Expand Up @@ -41,6 +41,14 @@ class PhoneNumber(str):
max_length: int = 64
"""The maximum length of the phone number."""

@classmethod
def __get_pydantic_json_schema__(
cls, schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
) -> dict[str, Any]:
json_schema = handler(schema)
json_schema.update({'format': 'phone'})
return json_schema

@classmethod
def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
return core_schema.general_after_validator_function(
Expand Down
17 changes: 17 additions & 0 deletions tests/test_phone_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,20 @@ def test_parse_error() -> None:
def test_parsed_but_not_a_valid_number() -> None:
with pytest.raises(ValidationError, match='value is not a valid phone number'):
Something(phone_number='+1 555-1212')


def test_json_schema() -> None:
assert Something.model_json_schema() == {
'title': 'Something',
'type': 'object',
'properties': {
'phone_number': {
'title': 'Phone Number',
'type': 'string',
'format': 'phone',
'minLength': 7,
'maxLength': 64,
}
},
'required': ['phone_number'],
}

0 comments on commit 843b753

Please sign in to comment.