Skip to main content
Type checking alone is only the beginning. In real applications you almost always need rules that go beyond “is this an integer?” — an age must be positive, a username must be between three and twenty characters, a discount must fall between 0 and 1. Pydantic’s 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.
Use @field_validator only when built-in constraints aren’t expressive enough. For simple range or length rules, Field() constraints are cleaner and self-documenting.

Built-in special types

Pydantic ships with validated types for common formats, so you don’t have to write regex validators yourself:
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, use ClassVar:

JSON Schema generation

Pydantic can generate a JSON Schema from your model. FastAPI uses this to power its automatic interactive documentation:
Output:

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.