Full answer
Pydantic v2 replaced v1's @validator and @root_validator with @field_validator and @model_validator.
@field_validator
@field_validator("roll_no")
@classmethod
def upper_roll(cls, v: str) -> str:
return v.strip().upper()- Must be a classmethod. Return the (possibly changed) value.
mode="after"(default): runs after type parsing, sovalready has the declared type.mode="before": runs on raw input, useful to accept "88%" and turn it into 88 before int parsing.mode="wrap"andmode="plain"exist for full control.- One validator can cover several fields:
@field_validator("first_name", "last_name"). info: ValidationInfogives access to already-validated fields (info.data), but field order then matters. Prefer a model validator for cross-field logic.
@model_validator
@model_validator(mode="after")
def check_dates(self) -> Self:
if self.end < self.start:
raise ValueError("end must be after start")
return selfmode="after": an instance method that receives the validated model. Returnself.mode="before": a classmethod that receives raw data (often a dict) and returns data. Use it to accept legacy input shapes.
Errors: raise ValueError (or PydanticCustomError for a custom type code). FastAPI returns 422; field validators report the field's location, model validators report the body.
Alternatives: reusable validators via Annotated[str, AfterValidator(func)] or BeforeValidator, which attach logic to a type instead of a model. Good when the same rule (like normalising phone numbers) applies in many models.
Keep validators pure and fast. Do not query databases in validators; check things like "email already registered" in the service layer, where you can return a proper 409.
from datetime import date
from typing import Annotated, Self
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import AfterValidator, BaseModel, field_validator, model_validator
def indian_mobile(v: str) -> str:
digits = "".join(ch for ch in v if ch.isdigit())[-10:]
if len(digits) != 10 or digits[0] not in "6789":
raise ValueError("must be a 10-digit mobile number")
return digits
Mobile = Annotated[str, AfterValidator(indian_mobile)]
class LeaveRequest(BaseModel):
roll_no: str
attendance: int
start: date
end: date
parent_mobile: Mobile
@field_validator("roll_no")
@classmethod
def normalise_roll(cls, v: str) -> str:
return v.strip().upper()
@field_validator("attendance", mode="before")
@classmethod
def strip_percent(cls, v):
return v.rstrip("%") if isinstance(v, str) else v
@model_validator(mode="after")
def check_dates(self) -> Self:
if self.end < self.start:
raise ValueError("end date must be on or after start date")
return self
app = FastAPI()
@app.post("/leave")
def apply(req: LeaveRequest):
return req
c = TestClient(app)
ok = {"roll_no": " bca-17 ", "attendance": "82%", "start": "2026-12-10", "end": "2026-12-12",
"parent_mobile": "+91 98765 43210"}
print(c.post("/leave", json=ok).json())
for bad in ({**ok, "parent_mobile": "12345"}, {**ok, "end": "2026-12-01"}):
for e in c.post("/leave", json=bad).json()["detail"]:
print(e["loc"], "->", e["msg"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. An after-model validator runs only when every field is valid, so the date error is shown with a separate request. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'roll_no': 'BCA-17', 'attendance': 82, 'start': '2026-12-10', 'end': '2026-12-12', 'parent_mobile': '9876543210'} ['body', 'parent_mobile'] -> Value error, must be a 10-digit mobile number ['body'] -> Value error, end date must be on or after start date
Key points
- field_validator for one field; model_validator for cross-field rules
- mode='before' sees raw input; mode='after' sees parsed values
- Field validators are classmethods returning the value
- After model validators return self
- AfterValidator/BeforeValidator attach logic to reusable types
Common mistakes
- Using v1's @validator and @root_validator in new v2 code
- Forgetting @classmethod on field validators or forgetting to return the value
- Doing cross-field checks in a field validator that depends on field order
- Querying the database inside validators
Follow-ups
- When would you use mode='before' rather than mode='after'?
- How do you reuse one validation rule across many models?
- Where should 'email already registered' be checked, and why not in a validator?
Tips
- Show both decorators with the right signatures
- Explain before and after modes with a concrete example
- Mention AfterValidator for reusable rules