Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Custom Validators and Types

Custom Field Validators

Write your own checks with @field_validator. Learn after and before modes, ValidationInfo, validating several fields, raising good errors and common mistakes.

Built-in types and Field constraints cover a lot: int, EmailStr, min_length, ge. Sooner or later a rule is specific to your business: a username may not contain spaces, a promo code must start with a year, a list of tags must be unique after lowercasing. For those, you write a validator, a function that Pydantic calls while it validates a field.

The decorator for a single field is @field_validator. This lesson shows the modes, how to read other fields, how to report errors that clients can understand, and the mistakes that catch most newcomers.

An after validator

By default a validator runs after Pydantic's own parsing, so it receives a value that already has the right type. You decorate a @classmethod, name the field(s), and either return the value (possibly changed) or raise an error.

Python A basic field validator

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.

Three details matter. The validator returns the value, and what it returns becomes the field's value, so forgetting return stores None. Raising ValueError (or AssertionError) turns into a ValidationError with the type value_error. And the message is prefixed with Value error, automatically.

flowchart LR
    I["input"] --> B["before validators"]
    B --> T["type check<br/>and conversion"]
    T --> A["after validators"]
    A --> R["field value"]

After validators see the parsed value, before validators see raw input.

Several fields, one validator

List the fields in the decorator, or use "*" for all of them. info.field_name tells you which field is being checked.

Python One validator for many fields

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.

Before validators: fix input first

A mode="before" validator runs first and receives whatever the caller sent, which might be a string, a list or None. Use it to normalize input into something Pydantic can parse, for example splitting a comma-separated string into a list.

Python Before mode for messy input

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 validator must accept every shape the caller might send, so check the type before you touch the value, and return it unchanged when you have nothing to do. After the before validator, Pydantic still checks that the result is a list[str].

Reading other fields: ValidationInfo.data

Validators run in the order fields are declared. A later field's validator can read earlier fields from info.data. This is how you check that a confirmation matches a password.

Python Comparing two fields

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 "password" in info.data check. If password itself failed validation, it is missing from info.data. A validator that assumes it is there would crash. When a rule involves several fields as equals, a model validator is usually clearer.

Wrap and plain modes

Two more modes exist for advanced cases. A wrap validator receives the value and a handler; it calls handler(value) to run Pydantic's normal validation and can act before and after it, or catch its errors. A plain validator replaces Pydantic's validation entirely, so you must do the type conversion yourself. They are shown with the Annotated style in Annotated Validators.

Reporting good errors

A plain ValueError is fine for most rules. When the client needs a stable code, raise PydanticCustomError with a type string and a message template:

Python Custom error types

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 type string (coupon_year) is what a front end can switch on, and the message can change without breaking it.

Common mistakes

  • Forgetting @classmethod under the decorator. Put @field_validator on top and @classmethod right below it.
  • Forgetting return. The validator's return value is the field value.
  • Assuming other fields exist. Check info.data for the key.
  • Validating in before mode without type checks. The input can be anything.
  • Expecting validators to run on defaults. They do not, unless you set validate_default=True on the Field.
  • Expecting validators on assignment. They run on assignment only with validate_assignment=True in the model configuration.
Python Defaults skip validators

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a field validator in the default (after) mode receive?

    After validators run once the type check and conversion succeeded. Before validators see the raw input.
  2. 2. A validator computes a cleaned value but has no return statement. What is stored in the field?

    The function's return value replaces the field value, and a function without return gives None.
  3. 3. Where do you find values of earlier fields inside a validator?

    ValidationInfo.data holds the already-validated fields, so always check that the key is present.
  4. 4. Which approach gives an error a stable machine-readable type?

    PydanticCustomError lets you choose the error type and the message template.

Summary

  • @field_validator("field") on a @classmethod adds a check; return the value, or raise ValueError.
  • Default mode is after parsing; mode="before" sees raw input and is best for normalizing; wrap and plain are advanced.
  • ValidationInfo gives field_name and data (earlier, valid fields).
  • Raise PydanticCustomError for stable error types.
  • Validators do not run on defaults or on assignment unless you enable them.

Next: Custom Model Validators