KevsRobots Learning Platform
40% Percent Complete
By Kevin McAleer, 2 Minutes

Pydanticβs powerful validation system can be extended with custom data types, enabling you to define bespoke validation logic and serialization/deserialization rules for specific data structures.
A custom data type in Pydantic is usually defined by extending existing base types and adding custom validation or transformation logic. Hereβs how you can create a custom type for handling email addresses:
from pydantic import BaseModel, EmailStr
class Email(EmailStr):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
# Place additional custom validation logic here
if not "@" in v:
raise ValueError("Invalid email address")
return v.lower()
This example shows a custom Email type that extends EmailStr, a built-in Pydantic type for email validation. It adds additional logic to ensure all emails are converted to lowercase.
Once youβve defined a custom data type, you can use it in your models just like any built-in type.
class User(BaseModel):
name: str
email: Email # Using the custom Email type
In this model, the email field uses the custom Email data type, applying both the built-in validation from EmailStr and the additional custom logic.
Define a custom data type for PhoneNumber that:
Use this custom type in a Contact model that includes fields for name and phone_number. Test your model with various phone number formats to ensure your validation and normalization logic works as expected.
You can use the arrows β β on your keyboard to navigate between lessons.
Comments