Cerberus Dict Validation With Schema
Validate nested dictionaries with Cerberus schemas for flexible form input validation.
Code
from cerberus import Validator
schema = {
'email': {'type': 'string', 'regex': r'^[^@\s]+@[^@\s]+\.[^@\s]+$', 'required': True},
'age': {'type': 'integer', 'min': 18, 'max': 120},
'tags': {'type': 'list', 'schema': {'type': 'string'}},
'metadata': {'type': 'dict', 'allow_unknown': True},
}
def validate(data):
v = Validator(schema)
if v.validate(data):
return {'valid': True, 'data': v.document}
return {'valid': False, 'errors': v.errors}What the code does
Cerberus Dict Validation With Schema comes down to the function validate.
From cerberus it pulls Validator — the imports name exactly which library surface the snippet touches.
It builds and returns a fresh value rather than reusing its inputs.
Watch out for
cerberusmust be installed first — the snippet imports it directly.
Applying it
Entry signature: def validate(data)
The surface worth importing is validate; the helpers around it are private to the snippet.
Statements that matter
return {'valid': False, 'errors': v.errors}
return {'valid': True, 'data': v.document}
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does `validate` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Does this require external packages?
- Yes — `cerberus`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.