Field Constraints with Field()
Field() lets you add constraints beyond just the type. Set minimum values, maximum lengths, patterns, and more.
from pydantic import BaseModel, Field
class User(BaseModel):
name: str = Field(min_length=1, max_length=50)
age: int = Field(ge=0, le=150) # ge = greater or equal
Now validation enforces these rules:
User(name="", age=30) # Error: name too short
User(name="Alice", age=-5) # Error: age below 0
Common constraints:
min_length,max_length- for stringsge,gt,le,lt- for numbers (greater/less than or equal)pattern- regex pattern for strings
You can also add descriptions and examples for documentation:
email: str = Field(description="User's email address", examples=["user@example.com"])
These show up in auto-generated API docs.
I cover Field constraints in depth in my Pydantic course.