Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Validation and Constraints

Field Constraints with Field()

Add rules to fields with Pydantic Field(): numeric bounds, string length, regex patterns, collection sizes, decimal digits, multiple_of, titles and descriptions.

A type tells Pydantic what kind of value to expect. A constraint adds a rule on top: the age is an int, and it must be at least 0. Constraints turn a model into a real contract for your data. You attach them with the Field() function, and you will use it in nearly every model.

Numeric constraints

Argument Meaning
gt greater than
ge greater than or equal
lt less than
le less than or equal
multiple_of must be a multiple of the number
Python Bounds on numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The error messages are generated for you and include the limits ("Input should be greater than 0"). Under the hood, the constraints run inside the fast Rust core, so they cost almost nothing.

String constraints

For str you have min_length, max_length and pattern (a regular expression that the whole value must match from the start). For text input also consider the model-wide config str_strip_whitespace=True, which removes spaces around values before checking.

Python Length and pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A regular expression is not a substitute for real parsing. Use pattern for simple shapes such as slugs or codes. For emails, URLs, IP addresses and so on use the dedicated types from Validating Special Types.

Collection constraints

Lists, sets, tuples and dicts accept min_length and max_length, so a model can require "at least one tag, at most five".

Python Sizes of collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can put constraints on the items too with Annotated (the next lesson).

Decimal digits

For Decimal, use max_digits (all digits) and decimal_places (digits after the point), which is exactly what a database NUMERIC(8, 2) column needs.

Python Money with two decimals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Documentation and metadata

Field also carries information for people and tools. These arguments do not validate anything but show up in the JSON Schema and, for FastAPI users, in the automatic API documentation.

Python Titles, descriptions, examples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the constraint gt=0 also appears in the schema as exclusiveMinimum, so clients and documentation tools see the same rule that your code enforces. JSON Schema has its own lesson.

Other useful Field arguments

Argument Purpose
default, default_factory default value (Optional Fields and Defaults)
alias a different key name in the input (Aliases and Naming)
strict disable conversion for this field (Strict Mode)
frozen forbid changing this field after creation
exclude leave the field out when dumping
repr whether the field shows in repr (set False for secrets)
deprecated mark a field as deprecated in the schema

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which constraint makes the value 0 invalid but 0.01 valid for a price?

    gt means strictly greater than. ge=0 would allow 0.
  2. 2. What does Field(min_length=1, max_length=3) do on a list field?

    On collections the length constraints apply to the number of items.
  3. 3. A Decimal field uses max_digits=8 and decimal_places=2. Which value fails?

    1.234 has three decimal places, more than the two allowed.
  4. 4. Does Field(description='...') change how values are validated?

    title, description and examples are metadata only.

Summary

  • Field() attaches constraints and metadata to a field.
  • Numbers: gt, ge, lt, le, multiple_of; strings: min_length, max_length, pattern; collections: min_length, max_length; decimals: max_digits, decimal_places.
  • Constraints are enforced by the fast core and generate clear error messages.
  • title, description and examples document the field and appear in the JSON Schema.
  • Prefer dedicated types over regex for emails, URLs and similar values.

Next: Annotated and Constrained Types