In Pydantic 2, how do you make a phone-number validator reusable across models, and when is @field_validator still the better choice?
answer
- rule travels with a named type
- AfterValidator in the metadata
- applies to each list item
- many fields, one method
- check_fields on a base class
basics
~10 sIn 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.
solid answer
~30 sI put the rule into a type: `PhoneNumber = Annotated[str, AfterValidator(normalise_phone)]`. Any model that declares a field as `PhoneNumber` gets the validator, `list[PhoneNumber]` applies it to every item, and the annotation itself shows which rules apply. Decorator validators are converted to the same markers internally, so behaviour matches. I still use `@field_validator` when one method should cover several fields of one model, or `'*'` for all of them, and on a base class with `check_fields=False` when subclasses declare the field. One trap either way: defaults are not validated unless `validate_default` is on, so a normalising validator skips a default value.
code
python · 27 linesfrom typing import Annotated
from pydantic import AfterValidator, BaseModel
def normalise_phone(value: str) -> str:
digits = ''.join(ch for ch in value if ch.isdigit())
if not 7 <= len(digits) <= 15:
raise ValueError('phone must hold 7 to 15 digits')
return '+' + digits
PhoneNumber = Annotated[str, AfterValidator(normalise_phone)]
class Guest(BaseModel):
phone: PhoneNumber
class Booking(BaseModel):
contact_phones: list[PhoneNumber]
print(Guest(phone='+1 (415) 555-0100'))
#> phone='+14155550100'
print(Booking(contact_phones=['415 555 0199', '+44 20 7946 0958']))
#> contact_phones=['+4155550199', '+442079460958']go deeper
Know that AfterValidator inside Annotated attaches a function to a field type, and that the function must return the value.
Explain reuse through a named alias, per-item validation in lists, and the cases where the decorator's multi-field and check_fields options fit better.
Reason about mixed stacking order, unvalidated defaults, and keeping shared validators pure so one alias behaves identically in every model.
Weigh a shared library of validated types against per-model decorators: consistency across services versus the coupling a central type module creates.
## Two ways to attach the same function Pydantic 2 lets you attach a validator function in two ways, and both produce the same internal result: - the **decorator pattern**, `@field_validator('phone')` on a class method inside one model; - the **annotated pattern**, a marker such as `AfterValidator(fn)` placed in the field's `Annotated[...]` metadata. Internally, decorator validators are converted into their annotated counterparts and appended to the field's metadata, so the two patterns obey the same rules. The difference is where the rule lives and how far it travels. ## Reuse through a named type The annotated pattern turns a rule into a **type you can name**: ```python PhoneNumber = Annotated[str, AfterValidator(normalise_phone)] ``` Every model that declares `phone: PhoneNumber` gets the rule, with no copy of the method and no inheritance between unrelated models. A guest model, a booking contact and a supplier record can share one definition of "a phone number", and the rule is visible at the point of use: reading the field annotation tells you which validators apply. Further consequences: 1. **Container items.** `contact_phones: list[PhoneNumber]` runs the validator on **each item**, not on the list as a whole. The decorator cannot do this directly; version 2's `@field_validator` has no `each_item` option. 2. **Stacking.** `Annotated[PhoneNumber, AfterValidator(other)]` adds a second rule on top of the first, in left-to-right order for after validators. 3. **Outside models.** The same alias works with `TypeAdapter` and in other places that accept a type, because the rule travels with the type, not with a model class. ## What the decorator does better | Need | Better fit | |---|---| | one rule across many fields of one model | `@field_validator('f1', 'f2')` or `'*'` | | a rule that needs other fields through `ValidationInfo` | either works; the decorator keeps it next to the fields | | a rule shared across models | `Annotated` alias | | a rule on every item of a list | `Annotated` alias on the item type | | a rule defined on a base class for fields that only subclasses declare | decorator with `check_fields=False` | By default `@field_validator` checks at class creation that every field it names exists on the model. `check_fields=False` turns that check off, which is meant for a validator on a base class whose field is expected to exist on subclasses. Passing `'*'` applies the validator to all fields, including those defined in subclasses. ## Mixing both on one field When a field carries an `Annotated` validator and a decorator validator, the decorator's is **appended after** the existing metadata. In practice: - a decorator **before** validator runs ahead of the annotation's before validators; - a decorator **after** validator runs after the annotation's after validators. That ordering surprises people who expect the class body to come "last" in every sense, so stating it is a good interview signal. ## Pitfalls to mention - **Defaults are not validated.** A field declared `phone: PhoneNumber = ' 555 0100 '` keeps that default untouched when the input omits it, because Pydantic does not validate defaults unless the field or model enables `validate_default`. A normalising validator therefore never touches an unvalidated default. - **Return the value.** An after validator that checks but forgets to `return value` sets the field to `None`, which then fails no check at all. - **Keep reusable validators pure.** A shared function should depend only on its input (and optionally `ValidationInfo`), not on one model's attributes; otherwise it is not really reusable. - What `Annotated` is as a Python typing construct belongs to the Python language material; here the subject is only what Pydantic does with validator markers inside it. ## The other markers you can put in the alias The same reuse works for every mode. `BeforeValidator` in an alias can strip formatting from raw input before the `str` check, `WrapValidator` can catch Pydantic's own error and retry, and `PlainValidator` replaces validation for that type entirely. A common shape for a phone type is two markers in one alias: a before validator that removes spaces and dashes, and an after validator that checks the digit count. Because before markers run right to left and after markers left to right, keeping each alias short, with one job per marker, keeps its behaviour easy to predict when another model stacks a further rule on top.
- In Pydantic 2, a field has an AfterValidator in its Annotated metadata and an after-mode @field_validator. Which runs first?The Annotated one. Decorator validators are converted to annotated markers and appended after the field's existing metadata, and after validators run left to right, so the decorator's after validator runs last. For before validators the effect reverses: the decorator's runs first.
- In Pydantic 2, how would you validate only the items of a list with a field validator?Annotate the item type, for example `list[Annotated[str, AfterValidator(fn)]]` or `list[PhoneNumber]`. Version 2's `@field_validator` has no per-item option, so a decorator validator on the field receives the whole list.
- Sharing a validator requires a common base model with the method.
- An AfterValidator on list[PhoneNumber] receives the whole list.
- A validator in the type also runs on an omitted field's default.
- Decorator validators always run after every Annotated validator.
- @field_validator accepts each_item=True for per-item checks.