Skip to content

12 Validation Deep

DodaTech 1 min read

title: Deep Validation in FastAPI REST APIs weight: 22 date: 2026-06-28 lastmod: 2026-06-28 description: Master advanced FastAPI validation with custom validators, nested model validation, conditional validation, cross-field validation, and custom error messages. tags: [api-development, fastapi]


Deep validation in FastAPI uses Pydantic's field_validator and model_validator for complex rules including cross-field validation, conditional validation, custom error messages, and nested model validation.

```python
from pydantic import BaseModel, Field, field_validator, model_validator
from typing import Optional
from datetime import date, datetime

class UserRegistration(BaseModel):
    username: str = Field(..., min_length=3, max_length=20, pattern="^[a-z0-9_]+$")
    email: str
    password: str = Field(..., min_length=8)
    confirm_password: str
    birth_date: Optional[date] = None
    accept_terms: bool = False

    @field_validator("email")
    @classmethod
    def validate_email(cls, v):
        if "@" not in v or "." not in v.split("@")[-1]:
            raise ValueError("Invalid email format")
        return v.lower()

    @field_validator("username")
    @classmethod
    def validate_username(cls, v):
        if v in ["admin", "root", "system"]:
            raise ValueError("This username is reserved")
        return v

    @model_validator(mode="after")
    def check_passwords_match(self):
        if self.password != self.confirm_password:
            raise ValueError("Passwords do not match")
        return self

    @model_validator(mode="after")
    def check_age_requirement(self):
        if self.birth_date:
            age = (date.today() - self.birth_date).days // 365
            if age < 13:
                raise ValueError("You must be at least 13 years old")
        return self

    @model_validator(mode="after")
    def check_terms(self):
        if not self.accept_terms:
            raise ValueError("You must accept the terms of service")
        return self

What's Next

Now learn about SQLAlchemy integration in Building REST APIs with FastAPI.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro