Course contentsShow
← AI Engineering
Lesson 770 of 1,88619. Structured Output and ValidationFree lesson

Custom Validators and Business Logic

Implement @validator decorators to add custom validation logic beyond type checking for domain-specific rules.

Custom Validators and Business Logic

You'll learn how to implement @validator decorators in Pydantic models to enforce domain-specific rules beyond what basic type checking can provide.

The Core Idea

Type constraints (like int, str, or even Literal types) ensure your data has the right shape, but they can't enforce business rules. Custom validators let you add logic like "email must be from company domain," "date must be in the future," or "price must be positive and less than $10,000."

Think of type checking as a bouncer checking IDs at a club entrance—they verify you have the right document. Custom validators are like a second check that verifies you're actually on the guest list, meet the dress code, and aren't banned.

How Validators Work

You attach a @validator decorator to a method in your Pydantic model. This method receives the field value and either returns it (if valid) or raises a ValueError (if invalid):

from pydantic import BaseModel, validator

class ProductOrder(BaseModel):
    product_name: str
    quantity: int
    unit_price: float
    
    @validator('quantity')
    def quantity_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('quantity must be greater than zero')
        return v
    
    @validator('unit_price')
    def price_must_be_reasonable(cls, v):
        if v < 0 or v > 10000:
            raise ValueError('price must be between $0 and $10,000')
        return v

When an LLM generates output matching this schema, Pydantic automatically runs your validators, catching business rule violations that type checking alone would miss.

Key Takeaway: Custom validators transform Pydantic models from simple type checkers into enforcers of your domain's business logic, ensuring LLM output meets real-world requirements beyond just having correct data types.