Explore lightweight, dictionary-based validation with Cerberus. Perfect for scenarios where you need flexible validation rules without heavy frameworks. Learn to define schemas, create custom validators, and validate complex data structures with minimal overhead.
This document explains a simple Cerberus example for validating user registration data.
The example demonstrates how to:
from cerberus import Validator schema = { 'username': {'type': 'string', 'minlength': 3, 'maxlength': 30}, 'email': {'type': 'string', 'regex': r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'}, 'age': {'type': 'integer', 'min': 18, 'max': 99}, 'interests': {'type': 'list', 'schema': {'type': 'string'}} }
This section imports the Validator class from Cerberus and defines the schema. The schema specifies the structure and constraints for each field in the user data.
v = Validator(schema)
Here, we create a Validator instance using the defined schema. This validator will be used to check the validity of user data.
user_data = { 'username': 'johndoe', 'email': 'john@example.com', 'age': 30, 'interests': ['python', 'data science', 'hiking'] } if v.validate(user_data): print("Data is valid!") else: print("Validation errors:", v.errors)
This section defines a valid user data dictionary and demonstrates how to use the validator to check it. If the data is valid, it prints a success message; otherwise, it displays the validation errors.
invalid_user = { 'username': 'jo', # too short 'email': 'not_an_email', # invalid email format 'age': 15, # under 18 'interests': ['python', 42] # 42 is not a string } if v.validate(invalid_user): print("Data is valid!") else: print("Validation errors:", v.errors)
This part demonstrates validation with invalid data. It intentionally includes errors to show how Cerberus handles and reports validation failures.
To run this example:
Ensure you have Cerberus installed:
pip install cerberus
Save the code in a file (e.g., cerberus_example.py)
Run the script:
python cerberus_example.py
The script will validate both the valid and invalid user data, printing the results of each validation.
validate method returns a boolean indicating whether the data is valid.errors attribute of the validator contains detailed error information.