Boolean validation rules
Pydantic validates booleans by accepting: valid bool instances (True or False), integers 0 or 1, strings that when converted to lowercase are one of '0', 'off', 'f', 'false', 'n', 'no', '1', 'on', 't', 'true', 'y', 'yes', and bytes objects that are valid per the string rule when decoded to a string.
String validation accepts multiple input types
Strings are accepted as-is. Bytes and bytearray are decoded to UTF-8 strings. Enums are converted using the value attribute by calling str() on it. If coerce_numbers_to_str is set in ConfigDict, any number type (int, float, Decimal) will be coerced to a string and accepted as-is.
String constraints
Strings support these constraints: pattern (a regex pattern the string must match), min_length (minimum string length), max_length (maximum string length), strip_whitespace (remove leading and trailing whitespace), to_upper (convert to uppercase), to_lower (convert to lowercase), ascii_only (allow only ASCII characters). These can be provided via StringConstraints metadata type or Field() function, except strip_whitespace, to_upper, to_lower, and ascii_only which must use StringConstraints or annotated-types predicates.
Regex engine configuration for pattern constraint
By default, Pydantic uses the regex Rust crate to enforce the pattern constraint. The regex engine can be controlled using the regex_engine configuration value in ConfigDict. If a compiled regular expression object is used for pattern, the Python engine will automatically be used.
Bytes validation rules
Bytes instances are validated as is. Strings and bytearray instances are converted as bytes, following the val_json_bytes configuration value in ConfigDict (despite its name, it applies to both Python and JSON modes).
Bytes constraints
Bytes support min_length (minimum length of bytes) and max_length (maximum length of bytes) constraints. These can be provided via Field() function or using MinLen and MaxLen metadata types from annotated-types library.
Integer validation rules
Integers are validated as-is. Strings and bytes are attempted to be converted to integers and validated as-is. Floats are validated as integers, provided the float input is not infinite or NaN and the fractional part is 0. Decimal instances are validated if they are finite and the denominator is 1. Fraction instances are validated if they are integers. Enums are converted using the value attribute.
Integer constraints
Integers support these constraints: le (value must be less than or equal to this number), ge (value must be greater than or equal to this number), lt (value must be strictly less than this number), gt (value must be strictly greater than this number), multiple_of (value must be a multiple of this number). These constraints can be provided using Field() function or using Le, Ge, Lt, Gt, MultipleOf metadata types from annotated-types library.
Pydantic constrained integer types in V2
Pydantic provides PositiveInt (requires input greater than zero), NegativeInt (requires input less than zero), NonPositiveInt (requires input less than or equal to zero), and NonNegativeInt (requires input greater than or equal to zero) types to further constrain allowed integer values.
Float validation rules
Floats are validated as-is. Strings and bytes are attempted to be converted to floats and validated as-is. If the input has a __float__() method, it will be called to convert the input into a float. If __float__() is not defined, it falls back to __index__(). This includes Decimal and Fraction types.
Float constraints
Floats support these constraints: le (value must be less than or equal to this number), ge (value must be greater than or equal to this number), lt (value must be strictly less than this number), gt (value must be strictly greater than this number), multiple_of (value must be a multiple of this number), allow_inf_nan (whether to allow NaN and infinite values). These can be provided using Field() function, annotated-types metadata types (Le, Ge, Lt, Gt, MultipleOf, IsFinite, IsNotFinite, IsNan, IsNotNan, IsInfinite, IsNotInfinite), or AllowInfNan type.
Pydantic constrained float types
Pydantic provides PositiveFloat (requires input greater than zero), NegativeFloat (requires input less than zero), NonPositiveFloat (requires input less than or equal to zero), NonNegativeFloat (requires input greater than or equal to zero), and FiniteFloat (prevents NaN and infinite values) types as convenience aliases.
Decimal validation rules
Decimal instances are validated as is. Any value accepted by the Decimal constructor is validated.
Decimal constraints
Decimals support these constraints (numbers must be coercible to decimals): le (value must be less than or equal to this number), ge (value must be greater than or equal to this number), lt (value must be strictly less than this number), gt (value must be strictly greater than this number), multiple_of (value must be a multiple of this number), allow_inf_nan (whether to allow NaN and infinite values), max_digits (maximum number of decimal digits allowed, zero before decimal point and trailing zeros not counted), decimal_places (maximum number of decimal places allowed, trailing zeros not counted). These can be provided using Field() function, Le, Ge, Lt, Gt, MultipleOf metadata types from annotated-types, or AllowInfNan type.
Decimal serialization in Python and JSON modes
In Python mode, Decimal instances are serialized as is. In JSON mode, they are serialized as strings.
Complex number validation rules
Complex instances are validated as-is. In Python mode, data is validated using the complex() constructor. In JSON mode, strings are validated using the complex() constructor, and numbers (integers and floats) are used as the real part.
Complex number serialization in Python and JSON modes
In Python mode, complex instances are serialized as is. In JSON mode, they are serialized as strings.
Fraction validation rules
Fraction instances are validated as is. Floats, strings and Decimal instances are validated using the Fraction() constructor.
Fraction serialization in Python and JSON modes
Fractions are serialized as strings, both in Python and JSON modes.
Pydantic constrained datetime types
Pydantic provides AwareDatetime (requires input to have a timezone), NaiveDatetime (requires input to not have a timezone), PastDatetime (requires input to be in the past when validated), and FutureDatetime (requires input to be in the future when validated) types to further constrain allowed datetime values.
Date validation rules
Date instances are validated as is. Strings and bytes are validated in two ways: (1) Strings complying to RFC 3339 date format, (2) Unix timestamps, both as seconds or milliseconds since the epoch. The val_temporal_unit configuration value in ConfigDict controls this. If validation fails, the input can be validated as a datetime (including as numbers), provided that the time component is 0 and that it is naive.
Pydantic constrained date types
Pydantic provides PastDate (requires input to be in the past when validated) and FutureDate (requires input to be in the future when validated) types to further constrain allowed date values.
Time validation rules
Time instances are validated as is. Strings and bytes are validated according to RFC 3339 time format. Integers and floats (or values that can be coerced to such numbers) are validated as seconds. The value should not exceed 86399.
Time serialization in Python and JSON modes
In Python mode, time instances are serialized as is. In JSON mode, they are serialized as strings.
Time constraints
Time supports these constraints (constraint values must be coercible to a time instance): le (value must be less than or equal to this time), ge (value must be greater than or equal to this time), lt (value must be strictly less than this time), gt (value must be strictly greater than this time). These can be provided using Field() function or using Le, Ge, Lt, Gt metadata types from annotated-types library.
Timedelta validation rules
Timedelta instances are validated as is. Strings and bytes are validated according to RFC 3339 time format. Integers and floats (or values that can be coerced to such numbers) are validated as seconds.
Timedelta serialization in Python and JSON modes
In Python mode, timedelta instances are serialized as is. In JSON mode, they are serialized as strings.
Timedelta constraints
Timedeltas support these constraints (constraint values must be coercible to a timedelta instance): le (value must be less than or equal to this timedelta), ge (value must be greater than or equal to this timedelta), lt (value must be strictly less than this timedelta), gt (value must be strictly greater than this timedelta). These can be provided using Field() function or using Le, Ge, Lt, Gt metadata types from annotated-types library.
Enum validation rules
If the enum.Enum type is used directly, any enum.Enum instance is validated as-is. If an enum.Enum subclass is used as a type, any enum member or value that corresponds to the enum members values is validated as-is.
Enum serialization in Python and JSON modes
In Python mode, enum instances are serialized as is. The use_enum_values configuration value in ConfigDict can be set to use the enum value during validation (so that it is also used during serialization). In JSON mode, enum instances are serialized using their value.
List validation rules
Lists allow list, tuple, set and frozenset instances, or any iterable that is not a string, bytes, bytearray, dict or mapping. Produces a list instance. If a generic parameter is provided, the appropriate validation is applied to all items of the list.
List constraints
Lists support these constraints: min_length (list must have at least this many items), max_length (list must have at most this many items). These can be provided using Field() function or using MinLen and MaxLen metadata types from annotated-types library.
Tuple validation rules
Tuples allow tuple, list, set and frozenset instances, or any iterable that is not a string, bytes, bytearray, dict or mapping. Produces a tuple instance. Appropriate validation is applied to items of the tuple, if element types are specified.
Tuple constraints
Tuples support these constraints: min_length (tuple must have at least this many items), max_length (tuple must have at most this many items). These can be provided using Field() function or using MinLen and MaxLen metadata types from annotated-types library.
NamedTuple validation rules
NamedTuples allow tuple and list instances. Validates each item according to the field definition. Allow dict instances. Keys must match the named tuple field names, and values are validated according to the field definition. Allow instances of the named tuple class (fields are revalidated).
NamedTuple serialization in Python and JSON modes
In Python mode, named tuples are serialized as tuples. In JSON mode, they are serialized as arrays.
Set and frozenset validation rules
Sets and frozensets allow set, frozenset, tuple and list instances, or any iterable that is not a string, bytes, bytearray, dict or mapping. Produces a set or frozenset instance. If a generic parameter is provided, the appropriate validation is applied to all items of the set/frozenset.
Set and frozenset constraints
Sets and frozensets support these constraints: min_length (set must have at least this many items), max_length (set must have at most this many items). These can be provided using Field() function or using MinLen and MaxLen metadata types from annotated-types library.
Deque validation rules
Values are first validated as a list, and then passed to the deque constructor.
Deque constraints
Deques support these constraints: min_length (deque must have at least this many items), max_length (deque must have at most this many items). These can be provided using Field() function or using MinLen and MaxLen metadata types from annotated-types library.
Deque serialization in Python and JSON modes
In Python mode, deques are serialized as is. In JSON mode, they are serialized as arrays.
Sequence validation rules
Any collections.abc.Sequence instance (except strings and bytes) is accepted. It is converted to a list using the list() constructor, and then converted back to the original input type. Strings and bytes are not accepted for the Sequence type.
Sequence constraints
Sequences support these constraints: min_length (sequence must have at least this many items), max_length (sequence must have at most this many items). These can be provided using Field() function or using MinLen and MaxLen metadata types from annotated-types library.
Sequence serialization in Python and JSON modes
In Python mode, sequences are serialized as is. In JSON mode, they are serialized as arrays.
Dictionary validation rules
Dict instances are accepted as is. Mapping instances are accepted and coerced to a dict. If generic parameters for keys and values are provided, the appropriate validation is applied.
Dictionary constraints
Dictionaries support these constraints: min_length (dictionary must have at least this many items), max_length (dictionary must have at most this many items). These can be provided using Field() function or using MinLen and MaxLen metadata types from annotated-types library.
TypedDict declaration and validation
TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys where each key is associated with a value of a consistent type. This type supports configuration. In strict mode, only dict instances are valid (unlike mappings in lax mode). Strict mode does not apply to the values of the typed dictionary; the strict constraint must be applied to the value types for this to work.
Iterable validation rules
Iterables are lazily validated, and wrapped in an internal data structure that can be iterated over (and will validate the items type while doing so). Even if you provide a concrete container such as a list, the validated type will not be of type list. Pydantic will ensure that the input value is iterable by getting an iterator from it (by calling iter() on the value).
Callable validation rules
Pydantic only validates that the input is a callable (using the callable() function). It does not validate the number of parameters or their type, nor the type of the return value.
Callable serialization
Callables are serialized as is. Callables can't be serialized in JSON mode (a PydanticSerializationError is raised).
UUID validation rules
UUID instances are validated as is. Strings and bytes are validated as UUIDs and casted to a UUID instance.
UUID version constraint
The UUID type supports a version constraint. The UuidVersion metadata type can be used. Pydantic also provides convenience aliases: UUID1, UUID3, UUID4, UUID5, UUID6, UUID7, UUID8.
UUID serialization in Python and JSON modes
In Python mode, UUIDs are serialized as is. In JSON mode, they are serialized as strings.
Type validation rules
Allows any type that is a subclass of the type argument. For instance, with type[str], allows the str class or any str subclass as an input. If no type argument is provided (i.e. type is used as an annotation), allow any class.
Type serialization
Types are serialized as is. Types can't be serialized in JSON mode (a PydanticSerializationError is raised).
Literal validation applies strict mode
Pydantic applies strict mode behavior when validating literal values.
Any type allows any value
The Any type (typing.Any or object) allows any value, including None.
Hashable validation rules
Any value that is hashable (using isinstance(value, Hashable)) is accepted for the Hashable type.
re.Pattern validation for regex patterns
For Pattern instances, Pydantic checks that the pattern attribute is of the right type (str or bytes depending on the Pattern type parameter). If the type parameter is str or bytes, input values of type str (or bytes respectively) are attempted to be compiled using re.compile().
re.Pattern serialization in Python and JSON modes
In Python mode, Pattern instances are serialized as is. In JSON mode, Pattern instances are serialized as strings.