111763 Views
85221 Views
83639 Views
51774 Views
49949 Views
48472 Views
Obsidian - the best tool for Makers
10 Projects for your Raspberry Pi Pico
Raspberry Pi Telegraf Setup with Docker
Setting Up Dynamic DNS on a Raspberry Pi for Self-Hosting
Raspberry Pi WordPress Setup with Docker
Raspberry Pi WireGuard VPN Setup with Docker
Using the Raspberry Pi Pico's Built-in Temperature Sensor
Getting Started with SQL
Introduction to the Linux Command Line on Raspberry Pi OS
How to install MicroPython
Wall Drawing Robot Tutorial
BrachioGraph Tutorial
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 >