Skip to content

Commit 843b753

Browse files
Added __get_pydantic_json_schema__ method with format='tel' (#106)
* 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 <[email protected]> --------- Co-authored-by: Marcelo Trylesinski <[email protected]>
1 parent a973b79 commit 843b753

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

pydantic_extra_types/phone_numbers.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from typing import Any, Callable, ClassVar, Generator
1010

11-
from pydantic import GetCoreSchemaHandler
11+
from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler
1212
from pydantic_core import PydanticCustomError, core_schema
1313

1414
try:
@@ -41,6 +41,14 @@ class PhoneNumber(str):
4141
max_length: int = 64
4242
"""The maximum length of the phone number."""
4343

44+
@classmethod
45+
def __get_pydantic_json_schema__(
46+
cls, schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
47+
) -> dict[str, Any]:
48+
json_schema = handler(schema)
49+
json_schema.update({'format': 'phone'})
50+
return json_schema
51+
4452
@classmethod
4553
def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
4654
return core_schema.general_after_validator_function(

tests/test_phone_numbers.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,20 @@ def test_parse_error() -> None:
5050
def test_parsed_but_not_a_valid_number() -> None:
5151
with pytest.raises(ValidationError, match='value is not a valid phone number'):
5252
Something(phone_number='+1 555-1212')
53+
54+
55+
def test_json_schema() -> None:
56+
assert Something.model_json_schema() == {
57+
'title': 'Something',
58+
'type': 'object',
59+
'properties': {
60+
'phone_number': {
61+
'title': 'Phone Number',
62+
'type': 'string',
63+
'format': 'phone',
64+
'minLength': 7,
65+
'maxLength': 64,
66+
}
67+
},
68+
'required': ['phone_number'],
69+
}

0 commit comments

Comments
 (0)