Phase 14 of 25 · Topic 14.5

Custom Pydantic Field Validators & Serializers

1Concept

Pydantic V2 provides `@field_validator` for single-field validation and normalization, and `@model_validator(mode='after')` for cross-field consistency checks.

2Architecture Diagram

field_validator('sku'): Ensures SKU starts with 'SKU-'
model_validator: Ensures confirm_password == password

3Code Example

Python 3.12
from pydantic import BaseModel, field_validator

class ProductPayload(BaseModel):
    sku: str
    price: float

    @field_validator("sku")
    @classmethod
    def validate_sku(cls, v: str) -> str:
        if not v.startswith("SKU-"):
            raise ValueError("SKU must start with 'SKU-' prefix")
        return v.upper()

prod = ProductPayload(sku="sku-99214", price=49.99)
print(f"Normalized SKU: {prod.sku}")

4Expected Output

Normalized SKU: SKU-99214

5Key Takeaways

  • In Pydantic V2, `@field_validator` must be a `@classmethod`.
  • Validators can modify and normalize the input value before returning it.
  • Use `mode='before'` to inspect raw input data before Pydantic type coercion.