108271 Views
83628 Views
56847 Views
48511 Views
47826 Views
47705 Views
Arduino Plug and Make Kit Review
Pi to Pico W Bluetooth Communication
Two-Way Bluetooth Communication Between Raspberry Pi Picos
Gamepad 2
Picotamachibi 2
Learning System updates
Introduction to the Linux Command Line on Raspberry Pi OS
How to install MicroPython
Wall Drawing Robot Tutorial
BrachioGraph Tutorial
Intermediate level MicroPython
Introduction to FreeCAD for Beginners
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 >