Skip to main content

Scalar and Temporal Types

Validate primitive data types like strings, numbers, and dates by defining schemas using pydantic_core.core_schema and passing them to a SchemaValidator.

from pydantic_core import SchemaValidator, core_schema

# Define a schema for a constrained string
schema = core_schema.str_schema(min_length=3, max_length=10, to_lower=True)
v = SchemaValidator(schema)

assert v.validate_python(' HELLO ') == 'hello'

String Validation

Use str_schema to validate and transform string data. It supports length constraints, regex patterns, and common transformations.

from pydantic_core import SchemaValidator, core_schema

v = SchemaValidator(
core_schema.str_schema(
min_length=2,
max_length=20,
pattern=r'^[a-z]+$',
strip_whitespace=True,
to_upper=True
)
)

assert v.validate_python(' pydantic ') == 'PYDANTIC'

Regex Engines

You can choose between two regex engines via the regex_engine parameter:

  • rust-regex (default): Fast and DDoS-resistant, but does not support backreferences or look-around.
  • python-re: Uses Python's standard re module, supporting all features but potentially slower.

Numeric Validation

Validate integers, floats, and decimals using range and multiple-of constraints.

Integers

int_schema handles integer validation and coercion from strings or floats in lax mode.

from pydantic_core import SchemaValidator, core_schema

v = SchemaValidator(core_schema.int_schema(ge=10, le=100, multiple_of=5))

assert v.validate_python(15) == 15
assert v.validate_python('20') == 20

Floats and Decimals

float_schema and decimal_schema provide similar constraints and include controls for special values like NaN and Infinity.

from decimal import Decimal
from pydantic_core import SchemaValidator, core_schema

# Float with infinity/nan control
v_float = SchemaValidator(core_schema.float_schema(allow_inf_nan=False))

# Decimal with precision constraints
v_decimal = SchemaValidator(
core_schema.decimal_schema(max_digits=5, decimal_places=2)
)
assert v_decimal.validate_python('123.45') == Decimal('123.45')

Boolean Validation

bool_schema validates boolean values. In lax mode (default), it coerces common string representations.

from pydantic_core import SchemaValidator, core_schema

v = SchemaValidator(core_schema.bool_schema())

assert v.validate_python('true') is True
assert v.validate_python(0) is False

Temporal Types

pydantic-core provides robust validation for dates, times, and durations, including timezone awareness and relative checks.

Datetime and Time

Use datetime_schema and time_schema to validate ISO8601 strings or native Python objects.

from datetime import datetime, timezone
from pydantic_core import SchemaValidator, core_schema

# Require a timezone-aware datetime
v = SchemaValidator(core_schema.datetime_schema(tz_constraint='aware'))

dt_str = '2023-10-27T12:00:00Z'
expected = datetime(2023, 10, 27, 12, 0, 0, tzinfo=timezone.utc)
assert v.validate_python(dt_str) == expected

Relative Constraints

You can enforce that a date or datetime is in the past or future using now_op.

from datetime import date
from pydantic_core import SchemaValidator, core_schema

v = SchemaValidator(core_schema.date_schema(now_op='past'))

# Assuming today is after 2000-01-01
assert v.validate_python(date(2000, 1, 1)) == date(2000, 1, 1)

Durations

timedelta_schema validates durations from ISO8601 strings or numeric seconds.

from datetime import timedelta
from pydantic_core import SchemaValidator, core_schema

v = SchemaValidator(core_schema.timedelta_schema(ge=timedelta(seconds=0)))

assert v.validate_python('PT1H') == timedelta(hours=1)
assert v.validate_python(3600) == timedelta(hours=1)

Global Configuration

You can apply default constraints across all scalar types in a schema by passing a CoreConfig to the SchemaValidator.

from pydantic_core import SchemaValidator, core_schema

config = core_schema.CoreConfig(
str_max_length=100,
allow_inf_nan=False,
strict=True
)

# This validator will inherit the config settings
v = SchemaValidator(core_schema.str_schema(), config)

Troubleshooting

Large Integer Limits

To prevent Denial of Service (DoS) attacks, pydantic-core limits string-to-integer conversion to strings of 4300 characters or fewer. Inputs exceeding this will raise a ValidationError.

Timezone Awareness

If tz_constraint='aware' is set, inputs without timezone information (like 2023-10-27T12:00:00) will fail validation. Conversely, tz_constraint='naive' will fail if a timezone is provided.

Microsecond Precision

For time, datetime, and timedelta, the microseconds_precision parameter (defaulting to 'truncate') determines how to handle sub-microsecond precision. Setting it to 'error' will raise a validation error if precision is lost.

v = SchemaValidator(core_schema.time_schema(microseconds_precision='error'))
# This will raise ValidationError because of the 7th decimal digit
# v.validate_python('12:00:00.1234567')