Validate API Reference¶
Auto-generated API documentation for the validate module.
validate
¶
Zero-dependency runtime validator for TypedDict and dataclass types.
Part of zerodep: https://github.com/Oaklight/zerodep Copyright (c) 2026 Peng Ding. MIT License.
Validate arbitrary data against stdlib type annotations (TypedDict, dataclass, Annotated constraints) and generate JSON Schema from the same type definitions.
Basic usage::
from validate import validate, json_schema, ValidationError
class User(TypedDict):
name: str
age: int
validate({"name": "Alice", "age": 30}, User) # ok
validate({"name": "Alice", "age": "x"}, User) # raises ValidationError
schema = json_schema(User) # {"type": "object", "properties": ...}
Annotated constraints::
from validate import Gt, MinLen
from typing import Annotated
class Item(TypedDict):
name: Annotated[str, MinLen(1)]
price: Annotated[float, Gt(0)]
Field validators (transform + validate)::
from validate import FieldValidator
def strip_lower(v: str) -> str:
v = v.strip().lower()
if not v:
raise ValueError("must not be empty")
return v
class User(TypedDict):
name: Annotated[str, FieldValidator(strip_lower)]
Model validators (cross-field validation)::
from validate import model_validator
class RegisterForm(TypedDict):
password: str
confirm: str
@model_validator(RegisterForm)
def passwords_match(data: dict) -> dict:
if data["password"] != data["confirm"]:
raise ValueError("passwords do not match")
return data
Gt
dataclass
¶
Value must be strictly greater than val.
Source code in validate/validate.py
Ge
dataclass
¶
Value must be greater than or equal to val.
Source code in validate/validate.py
Lt
dataclass
¶
Value must be strictly less than val.
Source code in validate/validate.py
Le
dataclass
¶
Value must be less than or equal to val.
Source code in validate/validate.py
MinLen
dataclass
¶
Length must be at least val.
Source code in validate/validate.py
MaxLen
dataclass
¶
Length must be at most val.
Source code in validate/validate.py
Match
dataclass
¶
Value must match pattern (via re.fullmatch).
Source code in validate/validate.py
Predicate
dataclass
¶
Value must satisfy a custom predicate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], bool]
|
A callable |
required |
description
|
str
|
Human-readable description for error messages. |
'custom predicate'
|
Source code in validate/validate.py
FieldValidator
dataclass
¶
Custom validator that can transform the field value.
Unlike Predicate (which returns bool), the function receives the
validated value and returns a (possibly transformed) value. Raise
ValueError or AssertionError to signal failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
A callable |
required |
description
|
str
|
Human-readable description for error messages. |
'custom validator'
|
Source code in validate/validate.py
ErrorDetail
dataclass
¶
A single validation error.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
Dotted/bracketed path to the failing field (e.g. |
expected |
str
|
Expected type or constraint description. |
actual |
str
|
Actual type or value description. |
message |
str
|
Human-readable error message. |
Source code in validate/validate.py
ValidationError
¶
Bases: Exception
Raised when validation fails.
Attributes:
| Name | Type | Description |
|---|---|---|
errors |
List of all validation errors found. |
Source code in validate/validate.py
model_validator(tp)
¶
Register a model-level validator for a TypedDict or dataclass type.
The validator receives the full data dict after all field validation
passes. It should return the (possibly modified) dict, or raise
ValueError / AssertionError on failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tp
|
type
|
The TypedDict or dataclass type to attach the validator to. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Callable], Callable]
|
A decorator that registers the function and returns it unchanged. |
Example::
class RegisterForm(TypedDict):
password: str
confirm: str
@model_validator(RegisterForm)
def passwords_match(data: dict) -> dict:
if data["password"] != data["confirm"]:
raise ValueError("passwords do not match")
return data
Source code in validate/validate.py
validate(data, tp, *, coerce=False)
¶
Validate data against type annotation tp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data to validate. |
required |
tp
|
Any
|
A TypedDict class, dataclass class, or any type annotation. |
required |
coerce
|
bool
|
If True, attempt type coercion (e.g. str to int). |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
The validated (and possibly coerced) data. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails, with all errors collected. |
Source code in validate/validate.py
json_schema(tp, *, title=None)
¶
Generate a JSON Schema dict from a type annotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tp
|
Any
|
A TypedDict class, dataclass class, or any type annotation. |
required |
title
|
str | None
|
Optional title for the schema root. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A JSON Schema dict (draft 2020-12 compatible subset). |