Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Custom Validators and Types

Custom Model Validators

Validate relationships between fields with @model_validator. Learn after, before and wrap modes, checking date ranges, either-or fields and rewriting input data.

A field validator looks at one field. Many real rules involve several fields at once: the end date must come after the start date, at least one of email and phone must be given, a discount may not exceed the price. Such rules belong to the whole model, and Pydantic gives you @model_validator for them.

A model validator has three modes. after runs once every field is valid and gives you the finished instance. before runs first and gives you the raw input. wrap surrounds the whole process. Most cross-field rules use after.

An after validator on the whole model

In mode="after" the function is an ordinary instance method. All fields are parsed and typed, so you can compare them directly. Return self at the end.

Python A date range check

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.

Look at the error location: it is an empty tuple, because the problem belongs to the model, not to one field. In an API response you might want to attach it to a field instead. You can do that by raising an error with a custom location through ValidationError.from_exception_data, though most projects accept the empty location and show the message as a form-level error.

Two things differ from field validators. The validator does not run if a field failed validation, because there is no finished instance to inspect. Pydantic reports the field errors and stops. And the method must return the instance, normally self.

Either-or rules

A very common rule: provide at least one of several optional fields.

Python At least one contact method

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.

Computing and filling fields

An after validator may also set derived values. Because assignment inside a validator does not trigger validation again (unless you turned on validate_assignment, which would recurse), use it for simple fills.

Python Derived field

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.

If a value is always computed from other fields, a @computed_field property is usually the better tool; the serialization chapter of this track covers it. A validator is better when the caller may supply the value.

Before validators: reshape the input

A mode="before" model validator is a @classmethod that receives the raw input, normally a dictionary, but possibly anything the caller passed. Use it to accept alternative input formats, rename keys or fill in values before field validation starts.

Python Accepting two input formats

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 input type is Any: always check with isinstance and return the value untouched when it is not yours to change. A before validator that assumes a dictionary will crash with a confusing TypeError when someone passes a list.

flowchart TB
    R["raw input"] --> MB["model validator: before"]
    MB --> F["field validation<br/>(types, field validators)"]
    F --> MA["model validator: after"]
    MA --> OK["finished model"]

Model validators wrap the field work: before on the way in, after on the way out.

Wrap validators

A wrap validator receives the input and a handler. It decides when to call the handler, can catch its ValidationError, and can post-process the result. It is the right tool when you want to recover from a failure, for example by trying a fallback.

Python A wrap validator with a fallback

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.

Swallowing errors hides problems, so use this sparingly and log what you did.

Choosing between field and model validators

Situation Use
One field, one rule @field_validator
Rule compares or combines fields @model_validator(mode="after")
Input arrives in several shapes @model_validator(mode="before")
Recover from errors, fallbacks @model_validator(mode="wrap")
Same rule on many fields across models An Annotated validator

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In mode="after", what does a model validator receive?

    An after validator is an instance method run once all fields are valid; it returns self.
  2. 2. What happens to an after model validator when one of the fields fails validation?

    There is no valid instance to inspect, so Pydantic reports the field errors first.
  3. 3. A before model validator receives input of type Any. What should it do with a value it does not understand?

    Return unknown input as is. Pydantic will then give a normal, helpful validation error.
  4. 4. Which rule is a good fit for a model validator?

    Comparing two fields needs the whole model. The other rules involve a single field and are handled by field validators or constraints.

Summary

  • @model_validator(mode="after") is an instance method that checks relationships between valid fields and returns self.
  • mode="before" is a classmethod on raw input: reshape or accept alternative formats, and pass unknown input through.
  • mode="wrap" gives you a handler to call, catch errors from and post-process.
  • Model errors have an empty loc; after validators do not run when field validation failed.

Next: Annotated Validators and Reusable Types