Skip to content
You're viewing docs for v2.3. See the latest version →

Functional Validators

This module contains related classes and functions for validation.

PydanticUserError

Bases: PydanticErrorMixin, TypeError

An error raised due to incorrect use of Pydantic.


AfterValidator

Usage docs: https://docs.pydantic.dev/2.2/usage/validators/#annotated-validators

A metadata class that indicates that a validation should be applied after the inner validation logic.

Attributes

func

Type: core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction


BeforeValidator

Usage docs: https://docs.pydantic.dev/2.2/usage/validators/#annotated-validators

A metadata class that indicates that a validation should be applied before the inner validation logic.

Attributes

func

Type: core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction


PlainValidator

Usage docs: https://docs.pydantic.dev/2.2/usage/validators/#annotated-validators

A metadata class that indicates that a validation should be applied instead of the inner validation logic.

Attributes

func

Type: core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction


WrapValidator

Usage docs: https://docs.pydantic.dev/2.2/usage/validators/#annotated-validators

A metadata class that indicates that a validation should be applied around the inner validation logic.

from datetime import datetime

from typing_extensions import Annotated

from pydantic import BaseModel, ValidationError, WrapValidator

def validate_timestamp(v, handler):
    if v == 'now':
        # we don't want to bother with further validation, just return the new value
        return datetime.now()
    try:
        return handler(v)
    except ValidationError:
        # validation failed, in this case we want to return a default value
        return datetime(2000, 1, 1)

MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]

class Model(BaseModel):
    a: MyTimestamp

print(Model(a='now').a)
#> 2032-01-02 03:04:05.000006
print(Model(a='invalid').a)
#> 2000-01-01 00:00:00

Attributes

func

Type: core_schema.NoInfoWrapValidatorFunction | core_schema.GeneralWrapValidatorFunction | core_schema.FieldWrapValidatorFunction


ModelWrapValidatorHandler

Bases: ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]

@model_validator decorated function handler argument type. This is used when mode='wrap'.


ModelWrapValidatorWithoutInfo

Bases: Protocol[_ModelType]

A @model_validator decorated function signature. This is used when mode='wrap' and the function does not have info argument.


ModelWrapValidator

Bases: Protocol[_ModelType]

A @model_validator decorated function signature. This is used when mode='wrap'.


ModelBeforeValidatorWithoutInfo

Bases: Protocol

A @model_validator decorated function signature. This is used when mode='before' and the function does not have info argument.


ModelBeforeValidator

Bases: Protocol

A @model_validator decorated function signature. This is used when mode='before'.


InstanceOf

Generic type for annotating a type that is an instance of a given class.


SkipValidation

If this is applied as an annotation (e.g., via x: Annotated[int, SkipValidation]), validation will be skipped. You can also use SkipValidation[int] as a shorthand for Annotated[int, SkipValidation].

This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes, and know that it is safe to skip validation for one or more of the fields.

Because this converts the validation schema to any_schema, subsequent annotation-applied transformations may not have the expected effects. Therefore, when used, this annotation should generally be the final annotation applied to a type.


field_validator

def field_validator(
    __field: str,
    fields: str = (),
    mode: Literal['before', 'after', 'plain'] = ...,
    check_fields: bool | None = ...,
) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]
def field_validator(
    __field: str,
    fields: str = (),
    mode: Literal['wrap'],
    check_fields: bool | None = ...,
) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]

Usage docs: https://docs.pydantic.dev/2.2/usage/validators/#field-validators

Decorate methods on the class indicating that they should be used to validate fields.

Returns

Callable[[Any], Any] — A decorator that can be used to decorate a function to be used as a field_validator.

Parameters

__field : str

The first field the field_validator should be called on; this is separate from fields to ensure an error is raised if you don’t pass at least one.

*fields : str Default: ()

Additional field(s) the field_validator should be called on.

mode : FieldValidatorModes Default: 'after'

Specifies whether to validate the fields before or after validation.

check_fields : bool | None Default: None

Whether to check that the fields actually exist on the model.

Raises

  • PydanticUserError
  • If @field_validator is used bare (with no fields).
  • If the args passed to @field_validator as fields are not strings.
  • If @field_validator applied to instance methods.

model_validator

def model_validator(
    mode: Literal['wrap'],
) -> Callable[[_AnyModelWrapValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]]
def model_validator(
    mode: Literal['before'],
) -> Callable[[_AnyModeBeforeValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]]
def model_validator(
    mode: Literal['after'],
) -> Callable[[_AnyModelAfterValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]]

Decorate model methods for validation purposes.

Returns

Any — A decorator that can be used to decorate a function to be used as a model validator.

Parameters

mode : Literal['wrap', 'before', 'after']

A required string literal that specifies the validation mode. It can be one of the following: ‘wrap’, ‘before’, or ‘after’.


FieldValidatorModes

Type: TypeAlias Default: Literal['before', 'after', 'wrap', 'plain']

ModelAfterValidatorWithoutInfo

A @model_validator decorated function signature. This is used when mode='after' and the function does not have info argument.

Default: Callable[[_ModelType], _ModelType]

ModelAfterValidator

A @model_validator decorated function signature. This is used when mode='after'.

Default: Callable[[_ModelType, _core_schema.ValidationInfo], _ModelType]

AnyType

Default: TypeVar('AnyType')