105800 Views
82496 Views
47243 Views
47066 Views
45458 Views
38527 Views
Pi-Apps
Intermediate MicroPython
Arduino Alvik
Raspberry Pi Time machine
Now Ad-Free
Guiding Light
Intermediate level MicroPython
Introduction to FreeCAD for Beginners
Building a Robot Arm with Raspberry Pi and PCA9685
Building User Authentication for Static Sites with FastAPI
Mastering Pydantic for Robust Data Validation
Mastering Markdown for Documentation with Jekyll
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.
Email
EmailStr
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.
email
Define a custom data type for PhoneNumber that:
PhoneNumber
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.
Contact
name
phone_number
< Previous Next >