Field() function lets you attach these constraints directly to your field declarations, keeping your validation logic co-located with your data definitions. When a value violates a constraint, Pydantic raises a ValidationError immediately, just as it does for type mismatches, and gives you a precise message pointing to the offending field.
The Field() function
Import Field from pydantic and use it as the default value for any field that needs constraints:
name must be between 1 and 100 characters; age must be greater than 0 and at most 120. Any violation raises a ValidationError the moment you instantiate the model.
String constraints
Control the length and format of string fields:Numeric constraints
Control the acceptable range of numeric fields:Default values with Field()
You can combine a default value with constraints in a single Field() call:
Common Field() usage patterns
Adding descriptions
Descriptions appear in generated JSON Schemas and are shown in FastAPI’s automatic docs:Custom validators
Built-in constraints handle most cases, but sometimes you need business logic. Use the@field_validator decorator:
The validator receives
cls (the class, because no instance exists during validation) and v (the incoming value). Return the value to accept it — optionally transformed — or raise ValueError to reject it.Built-in special types
Pydantic ships with validated types for common formats, so you don’t have to write regex validators yourself:- EmailStr
- HttpUrl
- Constrained list
Install the optional dependency:
pip install "pydantic[email]"Instance vs class attributes
When you need a constant shared across all model instances rather than a per-instance field, useClassVar:
JSON Schema generation
Pydantic can generate a JSON Schema from your model. FastAPI uses this to power its automatic interactive documentation:Real-world example: payment form validation
Real-world example: payment form validation
Learn more
What’s next?
You can now validate individual fields. Next, learn how to compose models inside other models to handle real-world hierarchical data.Nested Models
Learn how to handle complex, nested data structures with Pydantic.