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

Cross-Field Validation and Constraints

Implement custom validators that check relationships between fields and enforce business logic constraints.

Cross-Field Validation and Constraints

What you'll learn: How to validate that multiple fields in your structured output relate correctly to each other and satisfy business rules.

The Challenge of Field Relationships

So far, you've validated individual fields—checking that an age is positive or an email matches a pattern. But real-world data has relationships: a start_date must come before an end_date, a discount_percentage can't exceed the max_discount_limit, or a shipping_country might determine valid postal_code formats. These cross-field rules require custom validators that examine multiple fields together.

How Custom Validators Work

Building on Pydantic's custom validators (which you learned earlier), you create validators that access multiple fields using the @model_validator decorator. These validators receive the entire model's data and can check inter-field constraints:

from pydantic import BaseModel, model_validator
from datetime import date

class Event(BaseModel):
    start_date: date
    end_date: date
    max_attendees: int
    registered: int
    
    @model_validator(mode='after')
    def check_dates_and_capacity(self):
        # Cross-field date validation
        if self.end_date < self.start_date:
            raise ValueError('end_date must be after start_date')
        
        # Cross-field capacity validation
        if self.registered > self.max_attendees:
            raise ValueError('registered cannot exceed max_attendees')
        
        return self

When to Use Cross-Field Validation

Apply this pattern when business logic connects multiple fields: price calculations with taxes, hierarchical selections (country → state → city), mutually exclusive options, or data that must be internally consistent. Your LLM generates the JSON, but these validators ensure the relationships between values make sense.

Key Takeaway: Cross-field validators enforce business logic by examining multiple fields together, catching relationship errors that single-field validation can't detect—essential for ensuring your structured LLM output is not just well-formed, but logically valid.