# iron-monk - full docs (flat)
> Concatenated full documentation for iron-monk, in canonical reading order. Generated by support/build_llms.py - do not hand-edit. For a navigable index see llms.txt; for a token-trimmed digest see llms-ctx.txt.
---
# Quickstart
_Source: `docs/getting_started.md`_
# Getting Started
## Step 1: Installation
```bash
pip install iron-monk
```
!!! tip "Namespace"
The package is published as `iron-monk` but imported as `monk`. Always `import monk` (or `from monk import ...`) in your code.
## Step 2: Annotate Your Types
`iron-monk` provides the same toolkit across every Python surface — classes, functions, methods, raw dicts, and even standalone calls.
=== "Dataclasses"
```python
from typing import Annotated
from monk import monk
from monk.constraints import Email, Interval
@monk # (1)!
class User:
email: Annotated[str, Email]
age: Annotated[int, Interval(ge=18)]
```
1. The `@monk` decorator on a `class` converts it to a `dataclass` and locks attribute access until validation runs (see Step 3).
=== "Functions"
```python
from typing import Annotated
from monk import monk
from monk.constraints import Email, Interval
@monk # (1)!
def process_user(
email: Annotated[str, Email],
age: Annotated[int, Interval(ge=18)],
) -> None:
...
```
1. The `@monk` decorator on a function wraps it; arguments are validated immediately on every call.
=== "Methods"
```python
from typing import Annotated
from monk import monk
from monk.constraints import Email
class NotificationService:
@classmethod # (1)!
@monk # (2)!
def broadcast(cls, email: Annotated[str, Email]) -> None:
...
```
1. `@classmethod` is shown here, but `@staticmethod` and instance methods work the same way. Always place `@monk` **below** the binding decorator.
2. Arguments are validated immediately on every call, exactly like a free function.
=== "TypedDicts"
```python
from typing import Annotated, TypedDict
from monk.constraints import Email, Interval
class UserDict(TypedDict): # (1)!
email: Annotated[str, Email]
age: Annotated[int, Interval(ge=18)]
```
1. No decorator required — `iron-monk` reads constraints directly off the `TypedDict`. A `@monk` dataclass also works as a schema target.
=== "Standalone"
```python
from monk import validate_value # (1)!
from monk.constraints import Email, Len
```
1. `validate_value(value, *constraints)` runs one or more constraints against a single value. No class needed — useful for controllers, scripts, and one-shot checks (see Step 3). Every constraint also exposes a raw `.validate(value)` method for direct use.
---
## Step 3: Validate
`iron-monk` aggregates **every** field-level error into a single `ValidationError`. It does not fail-fast — pass an object with two bad fields and you get two errors back, not one.
`ValidationError.errors` is a `list[ErrorDict]` of `{field, message, code}`. Two helpers are available on every error:
- `.flatten()` — flat `["field: message", ...]` strings.
- `.to_rfc7807()` — RFC 7807 problem-detail dict for HTTP APIs.
=== "Dataclasses"
```python
from monk import validate
from monk.exceptions import ValidationError
user = User(email="bad-email", age=12) # (1)!
try:
validate(user) # (2)!
except ValidationError as e:
print(len(e.errors)) # 2 (3)!
# Happy path
good = validate(User(email="kai@example.com", age=30))
print(good.email) # (4)!
```
1. Instantiation is instant. By default, `iron-monk` defers validation until you call `validate()` — attribute access on an unvalidated instance raises `UnvalidatedAccessError`. Use `@monk(defer=False)` for fail-on-construct semantics.
2. Both `email` and `age` are invalid; both errors are collected.
3. Two errors, not one — `iron-monk` never fails fast.
4. After successful validation, attribute access is unlocked.
=== "Functions"
```python
from monk.exceptions import ValidationError
try:
process_user(email="bad-email", age=12) # (1)!
except ValidationError as e:
print(len(e.errors)) # 2
process_user(email="kai@example.com", age=30) # (2)!
```
1. Function arguments are validated eagerly on call.
2. Valid input — no exception, function runs normally.
=== "Methods"
```python
from monk.exceptions import ValidationError
try:
NotificationService.broadcast(email="bad-email")
except ValidationError as e:
print(e.flatten()) # ['email: Must be a valid email address.']
NotificationService.broadcast(email="kai@example.com") # (1)!
```
1. Methods validate exactly like free functions.
=== "TypedDicts"
```python
from monk import validate_dict
from monk.exceptions import ValidationError
try:
validate_dict({"email": "bad-email", "age": 12}, UserDict) # (1)!
except ValidationError as e:
print(len(e.errors)) # 2
validate_dict({"email": "kai@example.com", "age": 30}, UserDict) # (2)!
```
1. No object instantiation — `iron-monk` walks the raw dict against the schema.
2. Returns the validated dict on success. Pass `partial=True` for PATCH-style payloads or `drop_extra_keys=True` to strip unknown keys.
=== "Standalone"
```python
from monk import validate_value
from monk.constraints import Email, Len
from monk.exceptions import ValidationError
try:
validate_value("X", Len(min_len=3), Email) # (1)!
except ValidationError as e:
print(len(e.errors)) # 2 (2)!
validate_value("kai@example.com", Email) # (3)!
# Lower-level: skip aggregation, raise native ValueError/TypeError
Email().validate("bad-email") # (4)!
```
1. `validate_value` aggregates every per-constraint failure into a single `ValidationError` (same semantics as `validate()`). Use `field_name="..."` to customize the field label in `e.flatten()` output.
2. Both `Len` and `Email` fail — both errors collected, no fail-fast.
3. Happy path. Returns `None`; raises only on failure.
4. For raw single-constraint checks where aggregation is not needed, call the constraint's `.validate()` directly — it raises native `ValueError` / `TypeError`.
---
## Next Steps
- **[Core Concepts](concepts/index.md)** — the validation lifecycle, defer semantics, and error model.
- **[Constraints Toolkit](constraints/index.md)** — the full catalog of built-in constraints.
- **[Advanced Usage](advanced/index.md)** — cross-field rules, custom constraints, and framework integration.
---
# Concepts overview
_Source: `docs/concepts/index.md`_
# Core Concepts
`iron-monk` rests on a small philosophy and four pillars built on top of it. Read this page top-to-bottom for the *why*; click into each pillar for the deep-dive.
---
## Philosophy
Most validation libraries do too much. They coerce `"123"` into `123`, force you to inherit from a base class, and crash on the first error so you debug your payload one field at a time.
`iron-monk` flips all three:
- **Zero coercion.** If a string is not the right format, that is an error. Your data is never silently rewritten.
- **Zero base classes.** A `@monk` class is still a plain Python `dataclass`. No `BaseModel`, no metaclass tricks, no IDE slowdown.
- **Zero fail-fast.** Every field is checked. You get *every* error in one shot — no playing whack-a-mole.
- **Annotation is the schema.** Constraints live inside `typing.Annotated`. There is no separate model layer to keep in sync with your types.
Each pillar below reflects one of these choices.
---
## The Four Pillars
- **1 · [The `@monk` Decorator](decorator.md)**
---
One decorator. Three surfaces — classes, functions, methods. On classes it returns a regular `dataclass`; the rest of your code does not need to know `monk` exists.
- **2 · [Constraints](constraints.md)**
---
Plain classes with a single `validate(value) -> None` method. Stack them inside `typing.Annotated`. Compose with `AnyOf`, `Each`, `Ref`. Define your own in three lines.
- **3 · [Validation](validation.md)**
---
Three entry points matched to data shape: `validate()` for instances, `validate_dict()` for raw dicts, `validate_stream()` for iterables. Plus `validate_value()` for one-shot inline checks.
- **4 · [Errors](errors.md)**
---
Aggregated, not fail-fast. Three bad fields → three errors in one `ValidationError`. Includes `.flatten()` and `.to_rfc7807()` for HTTP APIs.
---
## Reading order
If this is your first time:
1. **[The Decorator](decorator.md)** — bind `@monk` to a class or function.
2. **[Constraints](constraints.md)** — write business rules with `Annotated`.
3. **[Validation](validation.md)** — pick the entry point that matches your data.
4. **[Errors](errors.md)** — collect every failure in one shot.
Each pillar is short (~50-100 lines) and self-contained. Skip ahead if a topic is already familiar.
---
## Next Steps
- **[Constraints Toolkit](../constraints/index.md)** — every built-in constraint with examples.
- **[Cross-Field Validation](../advanced/cross_field.md)** — `Ref` and the `__monk_validate__` hook.
- **[Customization](../advanced/customization.md)** — defining your own constraints in three lines.
- **[Settings & Type Metadata](../advanced/settings.md)** — unwrappers, type-keyed metadata, env vars for framework integration.
---
# Pillar 1 - The @monk Decorator
_Source: `docs/concepts/decorator.md`_
# 1 · The `@monk` Decorator
The single entry point for binding constraints to your code. It adapts to what it wraps.
## Why
Most validators force you to choose an architecture: a `BaseModel` for objects, a `Schema` class for dicts, a `validator()` decorator for functions. `@monk` is one decorator that covers all three surfaces — and on classes, it returns a regular `dataclass`, so the rest of your code does not need to know `monk` exists.
## How
| Wraps | Effect |
| --- | --- |
| `class` | Becomes a `@dataclass`. Validation is **deferred** by default — you call `validate(instance)` explicitly. Attribute access is locked until then. |
| `def` / `async def` | Wraps the call. Arguments and return value are validated **eagerly** on every invocation. |
| Method | Same as a function. Always place `@monk` *below* `@classmethod` / `@staticmethod`. |
```python
from monk import monk
@monk # deferred — call validate(user) yourself
class User: ...
@monk(defer=False) # eager — fails inside __post_init__
class StrictUser: ...
@monk
def process_user(...): ... # eager — fails on every call
```
## Gotchas
- **Deferred is the default for classes.** Touching `user.email` before `validate(user)` raises `UnvalidatedAccessError`. This is intentional: it lets you pass DTOs through layers and validate at the boundary (e.g. just before a DB write).
- **Globals.** `MONK_DEFER=false` (env var) or `settings.defer = False` (code) flip the default for the whole process.
- **Decorator order matters on methods.** `@classmethod` / `@staticmethod` must wrap *outside* `@monk`, otherwise binding breaks.
---
**Next:** [Pillar 2 — Constraints](constraints.md)
---
# Pillar 2 - Constraints
_Source: `docs/concepts/constraints.md`_
# 2 · Constraints
The business rules themselves — `Email`, `Interval`, `Len`, etc.
## Why
A constraint is just a class with one method: `validate(value) -> None`. That is the entire protocol. Anything that satisfies it can be used as a constraint — no registry, no metaclass, no plugin system. The toolkit stays small and trivially extensible.
## How
Stack constraints inside `typing.Annotated`. They run independently, in order, against the same value.
=== "Strings"
```python
from typing import Annotated
from monk.constraints import Len, LowerCase, Regex
Username = Annotated[str, Len(min_len=5, max_len=20), LowerCase, Regex(r"^\S+$")]
```
=== "Numbers"
```python
from typing import Annotated
from monk.constraints import Interval, MultipleOf
Score = Annotated[int, Interval(gt=0, le=100), MultipleOf(2)]
```
=== "Collections"
```python
from typing import Annotated
from monk.constraints import Email, Len
ContactList = Annotated[list[Annotated[str, Email]], Len(min_len=1, max_len=5)]
```
Constraints also compose with logical wrappers (`AnyOf`, `AllOf`, `Not`) and per-element wrappers (`Each`, `DictOf`). See **[Constraints → Composition](../constraints/composition.md)**.
**Per-element rules go inside the element type.** `iron-monk` recognizes annotated element types inside `list`, `set`, `tuple`, and `dict` and validates each item automatically:
```python
items: list[Annotated[int, Interval(gt=0)]]
mixed: list[Annotated[int, Interval(gt=0)] | Annotated[str, Len(min_len=1)] | None]
pair: tuple[Annotated[int, Interval(gt=0)], Annotated[str, Len(min_len=1)]]
links: dict[Annotated[str, LowerCase], Annotated[str, URL]]
```
Reach for the explicit `Each(...)` / `DictOf(...)` wrappers only when the container is untyped or you need to layer extra rules. See **[Constraints → Composition](../constraints/composition.md)**.
## Nullability
Constraints are **required by default**. Passing `None` to a constrained field raises a `NotNull` error.
```python
from typing import Annotated
from monk import monk
from monk.constraints import Email, Each, Len, Nullable, NotNull
@monk
class Profile:
email: Annotated[str, Email] # (1)!
nickname: Annotated[str, Len(max_len=10)] | None = None # (2)!
phone: Annotated[str, NotNull(message="Phone is required!"), Len(10)] # (3)!
tags: Annotated[list[str | None], Each(Nullable, Len(max_len=5))] # (4)!
```
1. Required. `None` raises `NotNull`.
2. Optional. `iron-monk` natively intercepts `| None` — no `Nullable` constraint needed at the field level.
3. Custom error message / code for missing data.
4. Inside `Each(...)` you must opt in with `Nullable` because `Each` runs constraints functionally over items.
??? info "Global Nullability (type-checker integration)"
To let a runtime type checker (e.g. `beartype`) own required-field enforcement, flip the default:
```bash
export MONK_DEFAULT_ALLOW_NONE=true
```
```python
from monk import settings
settings.default_allow_none = True
```
## Cross-field rules
Constraints can reference *sibling* fields with `Ref(...)`:
```python
from typing import Annotated
from monk import monk
from monk.constraints import Interval, Ref
@monk
class Range:
min_val: int
max_val: Annotated[int, Interval(gt=Ref("min_val"))]
```
`Ref` is resolved at validation time. See **[Cross-Field Validation](../advanced/cross_field.md)** for the full mechanic and the `__monk_validate__` hook.
## Custom constraints
The protocol is one method. To define your own, use the `@constraint` decorator:
```python
from monk import constraint
@constraint
class Even:
message: str | None = None
def validate(self, value):
if value % 2 != 0:
raise ValueError("Must be even.")
```
See **[Customization](../advanced/customization.md)** for message templating, code overrides, and refs in custom constraints.
## Gotchas
- **Constraints never coerce.** `Annotated[int, Interval(gt=0)]` does *not* parse strings. Pass the right type or expect a `TypeError`.
- **Order matters when constraints share a domain.** `Len(min_len=3)` before `LowerCase` will fail length first, lower-case second. Stable, but worth knowing.
- **`Each` does not consume iterators.** Passing a generator raises — convert to a list/tuple first, or use `validate_stream` (see [Pillar 3](validation.md)).
---
**Next:** [Pillar 3 — Validation](validation.md)
---
# Pillar 3 - Validation
_Source: `docs/concepts/validation.md`_
# 3 · Validation
Three entry points. Pick the one matching the data shape, not the framework.
## Why
Different stages of an application care about different shapes. Inside a service, you have objects. At an HTTP boundary, you have raw dicts. In a data pipeline, you have streams. Forcing all three to go through one entry point would mean instantiating objects you do not need or losing laziness.
## How
| Function | Input | When to use |
| --- | --- | --- |
| `validate(instance)` | A `@monk` class instance | Validate DTOs you have already built. Returns the (now-unlocked) instance for inline use. |
| `validate_value(value, *constraints)` | A single value + one or more constraints | Ad-hoc validation outside a `@monk` class — controllers, scripts, one-shot checks. |
| `validate_dict(data, schema)` | A raw `dict` + `TypedDict` / `@monk` class | High-throughput APIs that never instantiate objects. Supports `partial=True` (PATCH) and `drop_extra_keys=True` (sanitization). |
| `validate_stream(iterable, constraints)` | A generator / iterator | Lazy validation of large streams. The async sibling is `validate_async_stream`. |
```python
from monk import validate, validate_value, validate_dict, validate_stream
# Object: deferred until called explicitly
user = User(email="kai@example.com", age=30)
validate(user)
# Single value: skip the dataclass
validate_value(uploaded_body, MagicBytes(allowed=("image/png",)), FileSize(max_size=5_000_000))
# Dict: skip instantiation entirely
validate_dict({"email": "kai@example.com", "age": 30}, User)
# Stream: validate items as they are pulled
for item in validate_stream(big_generator, [Interval(gt=0)]):
process(item)
```
## Gotchas
- **`validate(instance)` is a no-op for non-monk classes.** It raises `TypeError` to surface accidental misuse rather than silently passing.
- **`validate_value` aggregates failures.** Every constraint runs, and all per-constraint errors land in a single `ValidationError`. Matches `validate()` semantics — not fail-fast.
- **`validate_dict` does not allocate the object.** Side effects in `__post_init__` will *not* fire — that is by design. Use `validate(MyClass(**data))` if you need them.
- **Streams are exhausted.** `validate_stream` yields each validated item; consume the generator.
For execution-time flags (partial, drop-extra-keys, recursive nesting) see **[Advanced → Execution Models](../advanced/execution.md)**.
---
**Next:** [Pillar 4 — Errors](errors.md)
---
# Pillar 4 - Errors
_Source: `docs/concepts/errors.md`_
# 4 · Errors
The unique selling point. Every other library on the JVM/Rust/Python market fails fast. `iron-monk` does not.
## Why
When a payload has three bad fields, your user wants to know all three at once, not one at a time as they fix each. Aggregation is the difference between a usable API and a frustrating one.
## How
A failed validation raises a single `ValidationError` carrying a list of `ErrorDict`:
```python
from monk import validate
from monk.exceptions import ValidationError
try:
validate(User(email="bad-email", age=12))
except ValidationError as e:
print(len(e.errors)) # 2 — both email and age are reported
print(e.errors[0]) # {"field": "email", "message": "...", "code": "Email"}
print(e.flatten()) # ["email: Must be a valid email address.", "age: ..."]
print(e.to_rfc7807()) # RFC 7807 problem-detail dict for HTTP APIs
```
Each `ErrorDict` carries:
- **`field`** — dotted path to the offending field. Nested fields look like `address.zip`; list items like `tags[2]`; dict values like `prefs['theme']`.
- **`message`** — human-readable, overridable per-constraint with `message=...`.
- **`code`** — stable machine-readable identifier (the constraint class name by default, or a custom `code=...`).
## Gotchas
- **Standalone `Constraint.validate()` is *not* aggregated.** It raises native `ValueError` / `TypeError` because there is no field context to aggregate over. Aggregation is a property of `validate` / `validate_value` / `validate_dict` / function-mode `@monk`.
- **`to_rfc7807()` defaults to HTTP 400.** Pass `status=`, `title=`, `type_uri=`, `instance=` to customize per route.
- **Error codes are class names by default.** If you alias a constraint (`MyEmail = Email`), the code stays `"Email"`. To override, set `code="..."` on the constraint instance.
---
## Next Steps
- **[Constraints Toolkit](../constraints/index.md)** — every built-in constraint with examples.
- **[Cross-Field Validation](../advanced/cross_field.md)** — `Ref` and the `__monk_validate__` hook.
- **[Customization](../advanced/customization.md)** — defining your own constraints in three lines.
- **[Settings & Type Metadata](../advanced/settings.md)** — unwrappers, type-keyed metadata, env vars for framework integration.
---
# Constraints catalog overview
_Source: `docs/constraints/index.md`_
# Constraints
Every business rule in `iron-monk` is a **constraint**: a small class with a single `validate(value) -> None` method. Constraints are attached to type hints with `typing.Annotated`. They never coerce, never mutate, and never fail-fast — every error is collected.
This section is the catalog. For the design rationale, see **[Core Concepts](../concepts/index.md)**.
---
## Anatomy of a Constraint
Every built-in constraint has a consistent shape:
```python
ConstraintName(
# Constraint-specific arguments
...,
# Optional kwargs available on every constraint
message: str | None = None,
code: str | None = None,
)
```
- **`message`** — overrides the default error string. Supports `{value}` and `{field_name}` format placeholders for any constructor argument (e.g. `Interval(ge=18, message="Must be at least {ge}")`).
- **`code`** — overrides the machine-readable error code (defaults to the constraint class name). Useful for stable client-side error matching.
Most constraints also accept **`Ref(...)`** in place of literal values to reference sibling fields. See **[Cross-Field Validation](../advanced/cross_field.md)**.
---
## Catalog
Constraints are grouped by data domain:
- **[Composition](composition.md)** — `AnyOf`, `AllOf`, `Not`, `When`, `Switch`, `Each`, `DictOf`, `Predicate`, per-element validation.
- **[Nullability](nullability.md)** — `Nullable`, `NotNull`.
- **[Strings](strings.md)** — `Blank`, `EndsWith`, `HexString`, `LowerCase`, `Match`, `MaxBytes`, `PathSafe`, `Trimmed`, …
- **[Format & Identity](format.md)** — `Email`, `URL`, `JWT`, `UUID`, `JSON`, `Base64`, `MimeType`, `Hash`, `CreditCard`, `ISBN`, `PEMBlock`, …
- **[Numeric](numeric.md)** — `Interval`, `MultipleOf`, `Even`/`Odd`, `Positive`/`Negative`, `NonZero`, `Port`, `PowerOfTwo`, …
- **[Equality & Choice](choice.md)** — `Eq`, `OneOf`.
- **[Collections](collections.md)** — `Len`, `Unique`, `Contains`, `Sorted`, `Subset`, `CSV`, `Nested`, …
- **[Datetime & Schedule](datetime.md)** — `Future`, `Past`, `IsTzAware`, `IsUTC`, `Cron`, …
- **[Filesystem](filesystem.md)** — `IsFile`, `IsDir`.
- **[File Uploads](uploads.md)** — `FileSize`, `MagicBytes`.
- **[Geospatial](geospatial.md)** — `LatLong`.
- **[Custom Messages & Constraints](custom.md)** — `{placeholder}` formatting, the `@constraint` decorator.
---
# Constraints / Composition
_Source: `docs/constraints/composition.md`_
# Composition
`iron-monk` ships logical wrappers and per-element wrappers so any constraint can be lifted into a richer context.
## `AnyOf`
`AnyOf(*constraints, message=None, code=None)`
Passes if **at least one** wrapped constraint passes.
```python
from monk.constraints import AnyOf, Email, URL
contact: Annotated[str, AnyOf(Email, URL)]
```
## `AllOf`
`AllOf(*constraints, message=None, code=None)`
Passes only if **every** wrapped constraint passes. Equivalent to stacking them inside `Annotated`, but useful when you need to wrap a group as a single unit (e.g. inside `Not`, `AnyOf`, or `Each`).
```python
from monk.constraints import AllOf, LowerCase, Trimmed
name: Annotated[str, AllOf(LowerCase, Trimmed)]
```
## `Not`
`Not(constraint, *, message=None, code=None)`
Inverts a constraint. Fails when the wrapped constraint passes.
```python
from monk.constraints import Not, Email
not_an_email: Annotated[str, Not(Email)]
```
## `When`
`When(field, test, then, else_=None, *, message=None, code=None)`
Conditional validation. Resolves `field` (typically a `Ref` to a sibling field), runs `test` against it, and applies `then` to the **current** field's value when `test` passes. If `test` fails and `else_` is provided, `else_` is applied instead. See **[Cross-Field Validation](../advanced/cross_field.md)** for end-to-end examples.
```python
from monk.constraints import When, Eq, Len, Ref
cc_number: Annotated[str, When(field=Ref("payment_method"), test=Eq("credit"), then=Len(min_len=16, max_len=16))]
```
## `Switch`
`Switch(field, cases, default=None, *, message=None, code=None)`
Multi-branch dispatch. Resolves `field` (typically a `Ref`) and applies the constraint mapped to that value in `cases`. Falls back to `default` when the discriminator is missing or unhashable; raises a `ValidationError` if neither matches. Sugar for chained `When` over a discriminated union.
```python
from monk.constraints import Switch, Email, Match, Len, Ref
target: Annotated[str, Switch(
field=Ref("channel"),
cases={"email": Email, "sms": Match(r"^\+\d+$")},
default=Len(min_len=1),
)]
```
## Per-Element Validation
Annotate the element type directly. `iron-monk` synthesizes per-element rules at decoration time for `list`, `set`, `frozenset`, `tuple`, and `dict`:
```python
from typing import Annotated
from monk.constraints import Email, Interval, Len
emails: list[Annotated[str, Email]]
ages: list[Annotated[int, Interval(ge=0)]]
mixed: list[Annotated[int, Interval(gt=0)] | Annotated[str, Len(min_len=1)] | None]
pair: tuple[Annotated[int, Interval(gt=0)], Annotated[str, Len(min_len=1)]] # heterogeneous
links: dict[Annotated[str, LowerCase], Annotated[str, URL]]
```
Use `T | None` inside the element annotation to allow `None` items.
## `Each`
`Each(*constraints)`
The explicit form. Reach for it when:
- The container is untyped (`list`, `dict`, plain `Annotated[list, ...]`).
- You want to layer **extra** rules on top of an inner-annotated container — supplying an outer `Each` short-circuits auto-synthesis to avoid double validation.
- You need the constraint as a value (e.g. inside `Not`, `AnyOf`, or as an argument to a custom helper).
Pass `Nullable` to allow `None` items, or `NotNull` to forbid them with a custom message.
```python
from monk.constraints import Each, Email, Nullable
emails: Annotated[list, Each(Email, Nullable)] # untyped list
```
## `DictOf`
`DictOf(*, key=None, value=None, message=None, code=None)`
The explicit form for dictionaries. Use it for untyped `dict` fields, or to layer extra rules on top of an annotated `dict[K, V]`. Either side accepts a single constraint or an iterable.
```python
from monk.constraints import DictOf, LowerCase, URL
links: Annotated[dict, DictOf(key=LowerCase, value=URL)]
```
## `Predicate`
`Predicate(func, *, message=None, code=None)`
Wraps any boolean-returning callable as a constraint. The fastest path to one-off rules.
```python
from monk.constraints import Predicate
def is_even(n: int) -> bool:
return n % 2 == 0
batch_size: Annotated[int, Predicate(is_even)]
```
---
# Constraints / Nullability
_Source: `docs/constraints/nullability.md`_
# Nullability
Constraints are **required by default**. Two markers control optionality.
## `Nullable`
`Nullable()` — marker that allows `None`. Required inside `Each(...)` since `Each` evaluates its constraints functionally.
## `NotNull`
`NotNull(*, message=None, code=None)` — marker that forbids `None` and lets you customize the missing-value error message or code.
For top-level fields, prefer the standard `T | None` syntax — `iron-monk` natively intercepts `Union` and bypasses validation for missing data. Full discussion in **[Core Concepts → Nullability](../concepts/constraints.md#nullability)**.
---
# Constraints / Strings
_Source: `docs/constraints/strings.md`_
# Strings
!!! tip "Bytes are accepted too"
Every string-typed constraint in this section (and [Format & Identity](format.md)) accepts `bytes` and `bytearray` in addition to `str`. Inputs are decoded as UTF-8 before validation; invalid UTF-8 raises a `ValueError`. This lets you validate raw network/protobuf payloads without manually decoding first.
## `Blank`
`Blank(*, message=None, code=None)` — requires the value to be empty or contain only whitespace. Combine with `Not` (`Not(Blank)`) for the inverse.
```python
placeholder: Annotated[str, Blank]
```
## `EndsWith`
`EndsWith(suffix, *, message=None, code=None)` — requires the value to end with `suffix`. Accepts `Ref`.
```python
avatar: Annotated[str, EndsWith(".png")]
```
## `HexString`
`HexString(length=None, *, message=None, code=None)` — value contains only hexadecimal characters. If `length` is set, the string must match it exactly.
```python
session_token: Annotated[str, HexString(length=64)]
```
## `IsAlnum` · `IsAlpha` · `IsAscii` · `IsDigit` · `LowerCase` · `Printable` · `UpperCase`
Predicate-backed string property checks. No constructor — use the bare instance. `Printable` rejects control characters (`\x00-\x1f`, `\x7f`); empty strings pass.
```python
from monk.constraints import LowerCase, IsDigit, Printable
slug: Annotated[str, LowerCase]
pin: Annotated[str, IsDigit]
display: Annotated[str, Printable]
```
## `Match`
`Match(pattern, *, message=None, code=None)` — requires the value to match a regex `pattern` (compiled once at construction).
```python
sku: Annotated[str, Match(r"^PROD-\d+$")]
```
## `MaxBytes`
`MaxBytes(max_bytes, *, message=None, code=None)` — UTF-8 encoded length must not exceed `max_bytes`. Accepts `str` (encoded to count) or raw `bytes` / `bytearray` (counted directly). Use for database column limits and API payload guards where character count diverges from byte count (CJK, emoji, accented Latin).
```python
bio: Annotated[str, MaxBytes(280)]
```
## `NoWhitespace`
`NoWhitespace(*, message=None, code=None)` — rejects strings containing any whitespace character (space, tab, newline, etc.).
```python
username: Annotated[str, NoWhitespace]
```
## `PathSafe`
`PathSafe(*, message=None, code=None)` — filename hardening: rejects path separators (`/`, `\`), null bytes, parent refs (`..`), the literal `.`/`..` filenames, and empty strings. Use for user-uploaded filenames, S3 key segments, traversal prevention.
```python
upload_name: Annotated[str, PathSafe]
```
## `SingleLine`
`SingleLine(*, message=None, code=None)` — rejects strings containing `\n` or `\r`. Tabs and other whitespace are allowed.
```python
log_message: Annotated[str, SingleLine]
```
## `StartsWith`
`StartsWith(prefix, *, message=None, code=None)` — requires the value to start with `prefix`. Accepts `Ref`.
```python
category: Annotated[str, StartsWith("cat_")]
```
## `Trimmed`
`Trimmed(*, message=None, code=None)` — rejects strings with leading or trailing whitespace.
```python
name: Annotated[str, Trimmed]
```
---
# Constraints / Format & Identity
_Source: `docs/constraints/format.md`_
# Format & Identity
Format-style string validators that check structural correctness only. They never coerce.
!!! tip "Bytes are accepted too"
These constraints also accept `bytes` and `bytearray` (decoded as UTF-8). See the [Strings page](strings.md) for the full bytes-handling note.
## `Base64`
`Base64(*, message=None, code=None)` — structurally validates a Base64 string.
## `DataURI`
`DataURI(*, message=None, code=None)` — RFC 2397 data URI (e.g., `data:image/png;base64,iVBOR...`). Structural only; does not decode the payload.
```python
embedded_image: Annotated[str, DataURI]
```
## `CreditCard`
`CreditCard(*, message=None, code=None)` — 13-19 digit string passing the Luhn checksum. Spaces and dashes are tolerated. Structural only — no issuer/network check.
```python
card_number: Annotated[str, CreditCard]
```
## `Email`
`Email(*, message=None, code=None)` — structural email check using the HTML5 living-standard atom regex. Local-part accepts the full RFC 5322 atom character set (``a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-``), matching the WHATWG `` validator. The domain must be a dotted hostname (at least one `.`), so single-label hosts like `user@localhost` are rejected. Quoted local parts and IP-literal domains (RFC 5321 §4.1.3) are intentionally out of scope; compose `AnyOf` with a custom `Match` if you need them.
```python
email: Annotated[str, Email]
```
## `Hash`
`Hash(algorithm, *, message=None, code=None)` — hex digest of fixed length per algorithm. Supported: `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2s`, `blake2b`. Algorithm name is case-insensitive.
```python
content_sha256: Annotated[str, Hash("sha256")]
```
## `HexColor`
`HexColor(*, message=None, code=None)` — `#RGB`, `#RGBA`, `#RRGGBB`, or `#RRGGBBAA`.
## `Hostname`
`Hostname(*, message=None, code=None)` — RFC 1123 hostname: each label 1-63 chars (alphanum + hyphen, no leading/trailing hyphen), total ≤253 chars. Single-label hostnames like `localhost` pass.
```python
host: Annotated[str, Hostname]
```
## `HttpURL`
`HttpURL(*, message=None, code=None)` — URL restricted to the `http` or `https` scheme. Use this when you specifically want to reject `ftp://`, `file://`, `javascript:`, etc.
```python
webhook_url: Annotated[str, HttpURL]
```
## `IPAddress`
`IPAddress(*, message=None, code=None)` — IPv4 or IPv6.
## `ISBN`
`ISBN(*, message=None, code=None)` — ISBN-10 or ISBN-13 with checksum verification. Spaces and dashes are tolerated; the trailing `X` check character is accepted for ISBN-10.
```python
book_isbn: Annotated[str, ISBN]
```
## `IsISO8601`
`IsISO8601(*, message=None, code=None)` — ISO 8601 date or datetime string. **Does not coerce** to a `datetime`.
## `JSON`
`JSON(*, message=None, code=None)` — accepts only strings that successfully parse as JSON. Does not return the parsed value.
## `JWT`
`JWT(*, message=None, code=None)` — JSON Web Token shape (`header.payload.signature`). Structural only — no signature verification.
## `MacAddress`
`MacAddress(*, message=None, code=None)` — `00:1A:2B:3C:4D:5E` or `-` separator.
## `MimeType`
`MimeType(*, message=None, code=None)` — RFC 6838 `type/subtype` with optional `; param=value` parameters. Validates the **string format** of a claimed mime header; for content sniffing of an actual file body, see [`MagicBytes`](uploads.md#magicbytes).
```python
content_type: Annotated[str, MimeType]
```
## `PEMBlock`
`PEMBlock(*, message=None, code=None)` — structurally validates a PEM-encoded block (X.509 cert, RSA/SSH key, etc.). Verifies the `-----BEGIN