How to Validate Forms with Pydantic in Python
Introduction
Pydantic v2 provides fast, type-safe data validation for Python. It’s the standard choice for FastAPI, CLI tools, and configuration management.
Step 1: Install Pydantic
pip install pydantic
Step 2: Define Models
from pydantic import BaseModel, EmailStr, field_validator
class UserForm(BaseModel):
email: EmailStr
password: str
age: int
@field_validator("password")
@classmethod
def validate_password(cls, v):
if len(v) < 8:
raise ValueError("Must be at least 8 characters")
if not any(c.isupper() for c in v):
raise ValueError("Must contain uppercase")
return v
@field_validator("age")
@classmethod
def validate_age(cls, v):
if v < 0 or v > 150:
raise ValueError("Invalid age")
return v
Step 3: Handle Errors
from pydantic import ValidationError
try:
user = UserForm(email="[email protected]", password="weak", age=25)
except ValidationError as e:
for error in e.errors():
print(f"Field: {error['loc']}, Message: {error['msg']}")
Conclusion
Pydantic v2 offers excellent performance and a clean API for data validation. The field_validator decorator gives you full control over validation logic, and the error system provides detailed feedback for users.