Field constraints and custom validators
Field constraints and custom validators
A type says what kind of thing a value is. It does not say that a ticket subject must be between three and two hundred characters, that an email must be lower-case, or that a closed ticket must carry a resolution. Those rules usually end up scattered through handlers as if statements, each with its own error message and each missed by at least one code path.
Pydantic lets you attach the rules to the field. Field() handles the common numeric and string constraints declaratively; field_validator runs your own function on one field; model_validator runs a function on the whole model when a rule spans several fields. All of them report through the same ValidationError, with the same loc paths, so a client gets one consistent list of problems.
Continue reading
Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.