diff --git a/pydantic_extra_types/phone_numbers.py b/pydantic_extra_types/phone_numbers.py index 4c25e452..f776cdc4 100644 --- a/pydantic_extra_types/phone_numbers.py +++ b/pydantic_extra_types/phone_numbers.py @@ -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: @@ -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( diff --git a/tests/test_phone_numbers.py b/tests/test_phone_numbers.py index 62fce284..1d3a1051 100644 --- a/tests/test_phone_numbers.py +++ b/tests/test_phone_numbers.py @@ -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'], + }