Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Custom Validators and Types

Annotated Validators and Reusable Types

Build reusable types with Annotated and AfterValidator, BeforeValidator, PlainValidator and WrapValidator, so one rule can be shared by many fields and models.

A @field_validator lives inside one model. If five models each have an email field that must be lowercased and trimmed, you would copy the validator five times. Pydantic offers a better way: attach the validator to the type itself with typing.Annotated. The result is a reusable type alias you can use anywhere, in models, in function signatures and inside lists.

Python
from typing import Annotated
from pydantic import AfterValidator

def lowercase(v: str) -> str:
    return v.lower()

LowerStr = Annotated[str, AfterValidator(lowercase)]

LowerStr is still a str for type checkers, but Pydantic runs lowercase whenever it validates a field of that type.

The four validator markers

Marker Runs Receives Use it for
BeforeValidator(f) before normal parsing raw input normalize messy input
AfterValidator(f) after normal parsing parsed value extra checks and cleaning
PlainValidator(f) instead of parsing raw input full control; you convert the type
WrapValidator(f) around parsing raw input and a handler recover, time, add behavior

They work like the decorator modes of field_validator, but they travel with the type.

AfterValidator: reusable checks

Define the function once and build named types from it. Notice that the type can be used in a list as well, where each element is validated.

Python Reusable cleaned 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 same two types are shared by both models, and the error for the list item shows its index: ('related', 1).

Stacking validators and constraints

An Annotated type can carry several markers. They run in order for after validators, and Pydantic's own constraints (Field, StringConstraints, annotated_types) live in the same list. Before validators run in reverse order, which keeps the nesting consistent: the last one added is the outermost.

Python Combining constraints and 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.

BeforeValidator: normalize input

A before validator sees raw input of any type. It must return something that normal parsing can accept. This type accepts either a list or a comma-separated string:

Python A list that accepts CSV text

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.

This is the fix for the "lists from the environment" problem in Settings Basics: use CsvList in a settings class and the variable TAGS=a,b,c works. (Pydantic-settings tries to decode complex fields as JSON first; the NoDecode annotation from pydantic_settings turns that off when you want to parse the text yourself.)

PlainValidator: you do the parsing

A plain validator replaces Pydantic's checking for that type. Whatever it returns is the value, so you are responsible for conversion and errors. It is useful for custom formats that no built-in type understands.

Python A hex color type

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.

Because the plain validator takes over, Pydantic cannot describe this type in a JSON Schema on its own (it only knows it is "something"); for schema-friendly custom types see Custom Types and Validation Context.

WrapValidator: around the standard parse

A wrap validator receives the value and a handler for the normal validation. You decide when to call it. Typical uses are fallbacks, defaults on failure, or measuring.

Python Falling back to a default on bad 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.

Use this sparingly. Quietly replacing bad input with zero hides real problems; do it only for fields where "unknown" truly means "zero".

Field-level versus type-level

Both styles can express the same rule. Choose by where the rule belongs:

  • A rule that is part of what the data means (a slug, a percentage, a country code) should be an Annotated type, defined once and imported everywhere.
  • A rule that exists only for one model or depends on its other fields is a field_validator or model validator.

Keep project-wide types in one module, for example types.py, so a change to the definition of a "slug" is a one-line edit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of an Annotated validator over @field_validator?

    An Annotated alias such as Slug is defined once and used in any model, list or function signature.
  2. 2. Which marker lets you replace Pydantic's own parsing completely?

    PlainValidator's return value is used as is, so you must convert and check the type yourself.
  3. 3. Query(tags="a,b") should give ['a', 'b']. Which marker fits for converting the string first?

    A string cannot be parsed as list[str], so the conversion has to happen before the normal validation.
  4. 4. What does a WrapValidator receive besides the value?

    You call handler(value) to run the standard validation, and may catch its errors or modify the result.

Summary

  • Annotated[type, Validator(func)] builds reusable types; use them in models, lists and signatures.
  • BeforeValidator normalizes raw input, AfterValidator checks parsed values, PlainValidator replaces parsing, WrapValidator surrounds it.
  • Markers can be stacked with Field, StringConstraints and other constraints.
  • Put shared types in one module; keep model-specific logic in decorators.

Next: Custom Types and Validation Context