Pydantic Field Validation & Validators
Explore advanced field validation options and create custom validators for complex business rules.
Why Validate with Pydantic?
Pydantic automatically validates data types in your models. But sometimes, you need more specific rules, like a minimum length for a username or a positive age.
This is where field validation and custom validators come in! They ensure your data meets all your application's business rules, making your APIs more reliable.
Using Pydantic's `Field` Function
Pydantic's Field function allows you to add extra validation rules and metadata to model fields. It's imported from pydantic. Let's see how to enforce a minimum and maximum length for a string.
from pydantic import BaseModel, Field
class User(BaseModel):
username: str = Field(min_length=3, max_length=15)
age: int
# Valid
try:
user1 = User(username="coddy", age=25)
print(f"Valid username: {user1.username}")
except Exception as e:
print(e)
# Invalid username (too short)
try:
user2 = User(username="c", age=30)
except Exception as e:
print(f"Error: {e}")All lessons in this course
- Pydantic Field Validation & Validators
- Custom Data Types & Settings
- Nested Models & Recursive Structures
- Serialization with model_dump and Aliases