Choosing a Python validation library
What each validation option is for, and which one fits the job in front of you.
There is no single best Python validation library, because the options solve different problems. Some turn data into typed objects, some check a dict against rules, and for a handful of fields you may not need a library at all.
The short answer
- A few fields in a script: write the checks by hand.
- Typed models, API request bodies, anything in FastAPI: Pydantic.
- Serialising objects to and from JSON, often with an ORM: Marshmallow.
- A schema that other languages or tools must share: jsonschema.
- Form or dict input where you want readable rules and every error message at once: Cerberus or nitro-validator.
Data validation in Python without a library
Plain if statements are a fine place to start. Collect the errors in a dict so the caller sees all of them, not just the first:
def validate_signup(data):
errors = {}
email = data.get("email", "")
if not email:
errors["email"] = "Email is required."
elif "@" not in email:
errors["email"] = "Email must contain an @."
age = data.get("age")
if not isinstance(age, int) or age < 18:
errors["age"] = "Age must be a whole number, 18 or more."
return errors
validate_signup({"email": "[email protected]", "age": 36}) # {}
validate_signup({"email": "ada", "age": 12})
This has no dependencies and anyone can read it. It stops being pleasant at around ten fields, or when the same checks appear in three places.
Dataclasses with post_init
A dataclass gives the data a shape, and __post_init__ runs straight after the object is built, so it is a natural place for checks:
from dataclasses import dataclass
@dataclass
class Signup:
email: str
age: int
def __post_init__(self):
if "@" not in self.email:
raise ValueError("email must contain @")
if not isinstance(self.age, int) or self.age < 18:
raise ValueError("age must be an integer of 18 or more")
Signup("[email protected]", 36) # Signup(email='[email protected]', age=36)
try:
Signup("ada", 36)
except ValueError as e:
print(e) # email must contain @
Two things to know. The type hints are not enforced: Signup("[email protected]", "36") only fails here because of the explicit isinstance check. And it stops at the first problem, which is fine for internal objects and awkward for a form.
The Python data validation libraries
Pydantic is the most widely used, and for good reason. You declare a class with type hints, and it parses, converts and validates input into an instance. It is fast, editors understand the models, and FastAPI is built on it. If you want typed objects out of untrusted input, this is the right answer.
from pydantic import BaseModel, Field
class Signup(BaseModel):
email: str
age: int = Field(ge=18)
signup = Signup.model_validate({"email": "[email protected]", "age": "36"})
signup.age # 36, converted to an int
Marshmallow defines a schema class separate from your objects, and works in both directions: load validates incoming data, dump serialises objects back out. It is common in Flask and SQLAlchemy projects where the same schema shapes the API in and out.
Cerberus validates a dict against a schema that is itself a dict, such as {"age": {"type": "integer", "min": 18}}. It is small, has no dependencies, and suits cases where the rules live in config or a database.
jsonschema implements the JSON Schema standard. Its strength is that the schema is portable: the same file can validate in Python, in JavaScript and in your API docs.
from jsonschema import validate
schema = {
"type": "object",
"properties": {"age": {"type": "integer", "minimum": 18}},
"required": ["age"],
}
validate(instance={"age": 36}, schema=schema)
Python validators compared
| Option | You write | You get back | Best for |
|---|---|---|---|
| Plain checks | if statements | Whatever you return | A few fields, no dependencies |
| Dataclass | A class and __post_init__ | An object, first error | Internal objects with a few invariants |
| Pydantic | A typed model class | A typed instance | APIs, settings, FastAPI |
| Marshmallow | A schema class | A dict or object | Loading and dumping, ORM projects |
| Cerberus | A schema dict | The dict, errors by field | Rules stored as data |
| jsonschema | A JSON Schema document | Pass or an exception | Schemas shared across languages |
| nitro-validator | Rule strings per field | The dict, errors by field | Forms and request dicts |
The shorter way with Nitro Validate
Nitro Validate sits at the small end of that table. Rules are pipe-separated strings, every rule runs, and the errors come back keyed by field with messages you can show to a user as they are:
from nitro_validator import Validator, ValidationError
validator = Validator()
rules = {
"email": "required|email",
"age": "required|integer|min:18",
"role": "required|in:admin,user",
}
try:
validator.validate({"email": "ada", "age": "12", "role": "root"}, rules)
except ValidationError as e:
print(e.errors)
# {'email': ['The email field must be a valid email address.'],
# 'age': ['The age field must be at least 18.'],
# 'role': ['The role field must be one of: admin, user.']}
clean = validator.validate({"email": "[email protected]", "age": "36", "role": "user", "debug": "1"}, rules)
clean # {'email': '[email protected]', 'age': '36', 'role': 'user'}
It has no dependencies and returns only the fields you listed rules for. It does not convert types: age stays the string "36". If you want an int and a typed object at the end, use Pydantic. If the data is a form or a config dict and what you need is good error messages, this is less code.
Common questions
Is Pydantic overkill for a small script? Often, yes. It is a real dependency with a compiled core. For five fields in a script, plain checks or a dataclass do the job. Once the data has nesting or you are building an API, it earns its place quickly.
What is the difference between validation and parsing? Validation answers "is this acceptable?" and leaves the data alone. Parsing turns it into something more useful, such as the string "36" into the integer 36. Pydantic and Marshmallow do both; Cerberus, jsonschema and nitro-validator mostly validate.
Should I validate in the browser or on the server? Both, for different reasons. Browser checks give quick feedback. Server checks are the ones that protect you, because anyone can send a request without your form.
This page uses Nitro Validate.
Validate data in one line. 51 built-in rules, zero dependencies, and pipe-string rules like required|email.
$ pip install nitro-validator