Docs / Guides / Validation engine

Platform 08 · Study guide

Validation engine

Validate request payloads with pipe rules before they reach your services.

What you will learn
  • How to call validate() with rule strings
  • How ValidationException becomes an API error
  • How to register a custom rule

1. Setup

from tpy.validation import validate, ValidationException, Validator
from tpy.http import ApiResponse

No extra dependency. Use in controllers/services on incoming dict payloads.

2. Basic usage

try:
    data = validate(
        payload,
        {
            "email": "required|email",
            "age": "required|integer|min:18",
            "password": "required|confirmed",
            "role": "nullable|in:admin,user",
        },
    )
except ValidationException as exc:
    return ApiResponse.validation_error(exc)

# data is the cleaned/accepted input
return ApiResponse.success(service.create(data))

3. How it works

  1. Rules are pipe-separated strings (required|email|min:3).
  2. The engine runs each rule in order for every field.
  3. On failure it raises ValidationException with per-field messages.
  4. ApiResponse.validation_error(exc) turns that into HTTP 422 JSON.
RuleExampleMeaning
requiredrequiredMust be present/non-empty
nullablenullable|emailSkip other rules when empty
email / uuid / urlemailFormat checks
integer / numeric / booleanintegerType checks
min / max / betweenmin:18Bounds
in / not_inin:admin,userAllow-list
confirmedconfirmedNeeds field_confirmation
regexregex:^[A-Z]+$Pattern

4. Custom rules

Validator.extend(
    "odd",
    lambda attr, value, data: int(value) % 2 == 1,
    "Value must be odd.",
)
Validator.make({"n": 3}, {"n": "odd"}).validate()