skip to content

Validators

field_validator and model_validator modes decide whether you see raw input or parsed values. Interviewers ask for a cross-field rule and how a ValidationError reports it.

on this pageshow

explore

questions

5

In Pydantic 2, what should a custom validator raise to reject a value, and what does the resulting ValidationError contain?

level: juniorimportance: must knowfreq 66%

answer

  1. do not raise the final error yourself
  2. assert vanishes under one flag
  3. type, loc, msg, input
  4. TypeError changed in version 2

basics

~10 s

A Pydantic 2 validator should raise ValueError (or PydanticCustomError); Pydantic collects it with other failures into one ValidationError whose errors() list gives each problem's type, loc, msg and input.

solid answer

~30 s

Raise `ValueError` with a clear message. Pydantic catches it, records an entry with `type` `'value_error'` and a `msg` prefixed `Value error, `, keeps validating other fields, and finally raises one `ValidationError`. `assert` also works and yields `assertion_error`, but asserts vanish under `python -O`, so I avoid them in production rules. `PydanticCustomError` from `pydantic_core` lets me choose a stable error type and message template. I never raise `ValidationError` myself, and a `TypeError` is no longer converted in version 2, it escapes as a bug. On the caller side, `errors()` returns dicts with `type`, `loc`, `msg`, `input`, optional `ctx` and `url`.

code

python · 24 lines
python
from pydantic import BaseModel, ValidationError, field_validator


class Guest(BaseModel):
    name: str
    phone: str

    @field_validator('phone')
    @classmethod
    def digits_only(cls, value: str) -> str:
        if not value.isdigit():
            raise ValueError('phone must contain digits only')
        return value


try:
    Guest(phone='555-0100')
except ValidationError as e:
    print(e.error_count())
    #> 2
    for err in e.errors(include_url=False):
        print(err['type'], err['loc'], err['msg'])
    #> missing ('name',) Field required
    #> value_error ('phone',) Value error, phone must contain digits only

go deeper

for a junior

Recall that validators raise ValueError, that Pydantic gathers every failure into one ValidationError, and that errors() lists type, loc and msg.

for a middle

Explain which exceptions Pydantic converts, why assert is risky under -O, and how loc paths into nested models and lists.

for a senior

Show judgment on error contracts: stable types with PydanticCustomError, keeping personal data out of logged errors, and stray exceptions escaping as bugs.

for a principal

Decide what error contract the team exposes, such as stable custom error types over message text, so clients and translations stay stable as rules change.

## What a validator raises, and what Pydantic does with it A Pydantic 2 validator never builds the final error itself. It raises a plain exception, Pydantic catches it, turns it into one **error entry**, and keeps validating the other fields. When the whole input has been processed, Pydantic raises a single **`ValidationError`** holding every entry. The docs are explicit that validation code should not raise `ValidationError` itself. ## The exceptions Pydantic converts | Raised in the validator | Resulting `type` | `msg` prefix | |---|---|---| | `ValueError` (the usual choice) | `value_error` | `Value error, ` | | `AssertionError`, from an `assert` | `assertion_error` | `Assertion failed, ` | | `PydanticCustomError(type, template, ctx)` | the type you chose | your template, filled from `ctx` | - **`ValueError`** is the standard choice: `raise ValueError('phone must hold 7 to 15 digits')`. - **`assert`** works, but `assert` statements are **removed when Python runs with `-O`**, so the check silently disappears in an optimised deployment. Treat it as a test convenience, not a production guard. - **`PydanticCustomError`**, imported from `pydantic_core`, is a `ValueError` subclass that lets you pick a stable machine-readable `type` such as `'phone_format'` and a message template, which helps clients and translations. ## What Pydantic does not convert Apart from Pydantic's own control exceptions, such as `PydanticUseDefault`, any other exception escapes as itself. A `KeyError` from reading a missing dict key, or an `AttributeError`, reaches the caller as a raw exception rather than a `ValidationError`, and the other collected errors are lost. `TypeError` is the notable case. In version 1 a `TypeError` raised inside a validator was wrapped into a `ValidationError`; in version 2 it **is no longer converted**, so a programming mistake such as calling a function with the wrong arguments surfaces as a bug rather than as a user-facing validation message. ## Reading `ValidationError` The exception offers several views: 1. `errors()` returns a list of dicts, one per problem, and accepts `include_url`, `include_context` and `include_input` keyword flags. 2. `error_count()` returns how many problems there were. 3. `json()` returns the same list as JSON. 4. `str(e)` gives a human-readable report, starting with a line like `2 validation errors for Guest`. Each entry from `errors()` carries these keys: - **`type`**: the machine-readable identifier, such as `value_error`, `missing` or `int_parsing`. Branch on this, not on the message. - **`loc`**: a tuple path to the problem. The first item is the field; nested models and list indexes follow, so `('guests', 2, 'phone')` means the third guest's phone. A model validator's error has an empty `loc`. - **`msg`**: the human-readable explanation. - **`input`**: the value that failed. - **`ctx`**: optional values used to render the message; for a `ValueError` it holds the original exception under `'error'`. - **`url`**: a link to the docs page for that error type. ## A worked booking example Suppose a booking request arrives with a missing guest name and a phone of `'555-0100'`, and the phone validator requires digits only. Pydantic does not stop at the missing name. It records a `missing` entry with `loc` `('name',)` and `msg` `Field required`, then runs the phone validator, catches its `ValueError`, and records a `value_error` entry with `loc` `('phone',)`. `error_count()` returns 2 and `str(e)` begins `2 validation errors for Guest`. If the same guest sat inside a booking's `guests` list at position 1, the phone entry's `loc` would be `('guests', 1, 'phone')`, which is exactly the path a client needs to highlight the right input. ## Practical consequences - Because errors are collected, one request can report a bad phone and a missing check-in date together, which is better for a form than fail-first behaviour. - `input` can contain personal data such as a guest's phone number; setting `hide_input_in_errors=True` in the model config keeps the input value and type out of the error's string form, which matters when errors are logged; `errors()` still returns `input` unless you call it with `include_input=False`. - How a web framework turns this list into an HTTP response is the framework's concern, not Pydantic's; Pydantic's job ends at a well-formed `ValidationError`.

  • In Pydantic 2, why use PydanticCustomError instead of a plain ValueError?
    A plain `ValueError` always produces `type` `'value_error'` with a `Value error, ` prefix, so clients can only tell rules apart by parsing text. `PydanticCustomError('phone_format', '{phone} is not a valid number', {'phone': v})` sets a stable type, a message template and `ctx` values, which a client can branch on or translate.
  • In Pydantic 2, what happens if a validator accidentally raises KeyError?
    Pydantic converts only `ValueError` (including its subclasses), `AssertionError` and a few Pydantic control exceptions. A `KeyError` escapes as a raw `KeyError`, so the caller gets a traceback instead of a `ValidationError`, and the errors collected for other fields are lost.

  • A validator should raise ValidationError directly to reject input.
  • assert is just as safe as raising ValueError in production.
  • Pydantic stops at the first invalid field and reports only that one.
  • A TypeError in a validator becomes a validation error in version 2.
  • Clients should branch on the msg text of each error.

Assumes Pydantic 2; version 1 wrapped a TypeError raised in a validator into a ValidationError, version 2 lets it propagate.

open as a page

In Pydantic 2, when do you use field_validator versus model_validator, and how would you enforce a check-out-after-check-in rule?

level: middleimportance: must knowfreq 74%

basics

~10 s

Pydantic 2's field_validator checks one field's value; model_validator sees the whole object. A check-out-after-check-in rule fits model_validator(mode='after'), which compares typed dates and reports its error with an empty loc.

open as a page

In Pydantic 2, how do you make a phone-number validator reusable across models, and when is @field_validator still the better choice?

level: middleimportance: should knowfreq 42%

basics

~10 s

In Pydantic 2, define an alias such as PhoneNumber = Annotated[str, AfterValidator(normalise_phone)] and use it in any model or list; keep @field_validator for one rule over several fields of one model.

open as a page

A Pydantic 2 booking model's check_out validator reads info.data['check_in'] and crashes with KeyError when check_in is invalid. Why, and how do you fix it?

level: seniorimportance: should knowfreq 32%

basics

~20 s

In Pydantic 2, a field that fails validation is left out of ValidationInfo.data, and a KeyError is not converted into a validation error, so it escapes. Read with info.data.get('check_in') and skip the rule when it is missing.

open as a page

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%

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.

open as a page