Cerberus Dict Validation With Schema

Validate nested dictionaries with Cerberus schemas for flexible form input validation.

PythonForm Validation

Code

pythonsnippet
14 lines
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

  • cerberus must 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

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.