skip to content

In Pydantic 2, how do before, after, plain and wrap field validators differ in what they receive and when they run?

level: seniorimportance: should knowfreq 50%

answer

  1. position around the core type check
  2. raw input versus typed value
  3. one mode skips the type check
  4. a handler argument
  5. right to left, then left to right

basics

~20 s

Pydantic 2 field validator modes place your function around its type check: before gets raw input that is then type-checked, after gets the typed value, plain replaces the check entirely, and wrap gets a handler it may call, retry or skip.

solid answer

~40 s

An `after` validator, the decorator default, runs once Pydantic has validated the value against the annotation, so it receives a typed value. A `before` validator gets the raw input, which can be any object, and whatever it returns is still validated against the type. A `plain` validator also gets raw input but ends validation when it returns, so Pydantic never checks the result against the annotation. A `wrap` validator receives the raw input plus a `handler`; calling `handler(value)` runs normal validation, which you can wrap in `try`/`except`, retry with a fixed value, or skip. With the `Annotated` markers, before and wrap validators run right to left, then after validators left to right, and decorator validators are appended after the annotation's.

code

python · 26 lines
python
import re
from typing import Any

from pydantic import BaseModel, field_validator


class Guest(BaseModel):
    phone: str

    @field_validator('phone', mode='before')
    @classmethod
    def strip_formatting(cls, value: Any) -> Any:
        if isinstance(value, str):
            return re.sub(r'[\s().-]', '', value)
        return value

    @field_validator('phone', mode='after')
    @classmethod
    def check_digits(cls, value: str) -> str:
        if not re.fullmatch(r'\+?\d{7,15}', value):
            raise ValueError('phone must hold 7 to 15 digits')
        return value


print(Guest(phone='+1 (415) 555-0100'))
#> phone='+14155550100'

go deeper

for a junior

Remember that after is the default mode and receives a value of the declared type, and that before receives raw input.

for a middle

Explain all four modes by what they receive and whether Pydantic's type check runs, and pick the right one for normalising input.

for a senior

Reason about stacking order with Annotated and decorators, the plain mode's lost type safety, and why a JSON Schema can misstate accepted input.

for a principal

Decide when a team should allow plain or wrap validators at all, since each one moves type safety out of Pydantic and into hand-written code.

## Where a validator sits relative to Pydantic's own parsing Every Pydantic 2 field has a core step: validating the input against the annotation, for example turning `'42'` into `42` for an `int` field in lax mode. A custom field validator is placed **around** that step, and its **mode** says where. The mode is set with `@field_validator('phone', mode=...)` or by choosing one of four `Annotated` markers: `BeforeValidator`, `AfterValidator`, `PlainValidator`, `WrapValidator`. ## The four modes | Mode | Receives | Pydantic's type check | Typical use | |---|---|---|---| | `after` (decorator default) | the parsed, typed value | already done, before your function | rules on a correct type | | `before` | the raw input, any object | runs on whatever you return | normalising raw input | | `plain` | the raw input | **never runs** | replacing validation entirely | | `wrap` | the raw input plus a `handler` | runs when you call `handler(value)` | try, catch, retry or short-circuit | - **After** validators are the safest: the value already has the declared type, so you write ordinary typed code. The function must return the value: an after validator that only checks and forgets `return value` sets the field to `None`. - **Before** validators must cope with anything: a phone number may arrive as a string, an int or a list. Whatever they return is then validated against the annotation, so returning the wrong type still fails cleanly. - **Plain** validators act like before validators but **terminate validation** when they return: no further validators run and Pydantic does not check the result against the type. A field annotated `int` can end up holding a string. - **Wrap** validators take a mandatory `handler` (`ValidatorFunctionWrapHandler`). Calling `handler(value)` runs Pydantic's validation and any inner validators; you may wrap that call in `try`/`except ValidationError`, call it again with a repaired value, or not call it at all. ## A worked case: guest phone numbers A booking accepts `'+1 (415) 555-0100'`, `'415.555.0100'` and sometimes a bare integer. A sound design uses two validators on one field: 1. A **before** validator strips spaces, brackets, dots and dashes when the input is a string, and passes anything else through untouched. 2. Pydantic's core step then requires a `str`. An integer is rejected here, because lax mode does not turn numbers into strings unless `coerce_numbers_to_str` is enabled. 3. An **after** validator checks the cleaned string against a digit pattern and raises `ValueError` if it fails. Doing the cleanup in an after validator would be too late for any check that runs in the core step; doing the digit check in a before validator would force you to handle every possible input type yourself. ## Ordering when several validators stack For the `Annotated` form, the documented rule is: - **before** and **wrap** validators run **right to left**; - then the core step; - then **after** validators run **left to right**. So in `Annotated[str, AfterValidator(a), AfterValidator(b), BeforeValidator(c), WrapValidator(d)]`, the order is `d`, `c`, core, `a`, `b`. Validators declared with `@field_validator` are converted to the same markers and **appended after** the field's existing metadata, so a decorator's before validator runs ahead of the annotation's before validators, and a decorator's after validator runs after the annotation's after validators. ## Costs and traps - A before validator that mutates its input and then raises can leak the mutated value into the next member of a union, which the docs warn against. - Before, plain and wrap validators can accept inputs the annotation does not describe, so the JSON Schema can lie; `json_schema_input_type` declares the real accepted input. A plain validator's schema input defaults to `Any`. - Default values are not validated unless the field enables it, so none of these modes runs on an omitted field's default. - A plain validator is rarely the right first choice: you take over all checking for that field, including the type. ## Choosing a mode, in order of preference 1. Start with **after**: typed input, least code, and Pydantic has already rejected wrong types. 2. Use **before** when the raw input needs reshaping that Pydantic's own parsing would reject, such as stripping formatting or wrapping a single value in a list. 3. Use **wrap** when you need to see Pydantic's own error and react to it, for example truncating an over-long string and validating again, or logging failures for one field. 4. Use **plain** only when you deliberately replace validation for that field, and accept that the annotation no longer guarantees the stored type.

  • In Pydantic 2, what can a wrap validator do that before and after validators together cannot?
    It can react to Pydantic's own failure. Wrapping `handler(value)` in `try`/`except ValidationError` lets it inspect the error type, for example `string_too_long`, and call the handler again with a repaired value, or return early without validating at all. Before and after validators never see the core step's error.
  • In Pydantic 2, why might model_json_schema() misdescribe a field that has a before validator?
    The schema is generated from the annotation, but a before, plain or wrap validator may accept other input, such as an int for a `str` field. Passing `json_schema_input_type` to the validator declares the real accepted input; for plain validators it defaults to `Any`, because the field type is discarded.

Think of a hotel check-in desk. A before validator is the porter who tidies a guest's forms before the clerk checks them; an after validator is the manager who reviews forms the clerk approved; a plain validator is a porter who files the form himself so the clerk never sees it; a wrap validator is a supervisor who hands the form to the clerk, watches the result, and may send it back corrected.

  • A before validator receives a value already converted to the field type.
  • A plain validator's return value is still checked against the annotation.
  • Validators always run in the order they are written.
  • A wrap validator must always call its handler.
  • Before mode is the default for @field_validator.