0
# Core Validation
1
2
The Validator class is the heart of Cerberus, providing comprehensive document validation and normalization capabilities against schema definitions. It supports extensive validation rules, custom constraints, and flexible validation modes.
3
4
## Capabilities
5
6
### Validator Class
7
8
The main validation class that validates and normalizes mappings against validation schemas.
9
10
```python { .api }
11
class Validator:
12
def __init__(self, schema=None, ignore_none_values=False, allow_unknown=False,
13
require_all=False, purge_unknown=False, purge_readonly=False,
14
error_handler=None):
15
"""
16
Initialize a Validator instance.
17
18
Parameters:
19
- schema: Validation schema (dict or string reference)
20
- ignore_none_values: Skip validation of None values (bool)
21
- allow_unknown: Allow unknown fields (bool or dict)
22
- require_all: Require all schema fields (bool)
23
- purge_unknown: Remove unknown fields during validation (bool)
24
- purge_readonly: Remove readonly fields during normalization (bool)
25
- error_handler: Custom error handler instance or class
26
"""
27
```
28
29
### Document Validation
30
31
Core validation functionality for validating documents against schemas.
32
33
```python { .api }
34
def validate(self, document, schema=None, update=False, normalize=True) -> bool:
35
"""
36
Validate a document against the schema.
37
38
Parameters:
39
- document: The document to validate (dict)
40
- schema: Override schema for this validation (dict, optional)
41
- update: Treat document as an update, allowing partial validation (bool)
42
- normalize: Apply normalization during validation (bool)
43
44
Returns:
45
bool: True if valid, False otherwise
46
"""
47
48
def validated(self, *args, **kwargs):
49
"""
50
Return validated document or None if validation failed.
51
52
Parameters: Same as validate(), plus:
53
- always_return_document: Return document even if validation fails (bool, default: False)
54
55
Returns:
56
dict or None: Validated document if successful, None if validation failed
57
(unless always_return_document=True)
58
"""
59
60
def __call__(self, document, schema=None, update=False, normalize=True) -> bool:
61
"""
62
Callable interface - alias for validate().
63
64
Parameters: Same as validate()
65
66
Returns:
67
bool: True if valid, False otherwise
68
"""
69
```
70
71
### Document Normalization
72
73
Document transformation and coercion capabilities.
74
75
```python { .api }
76
def normalized(self, document, schema=None, always_return_document=False):
77
"""
78
Return normalized version of document.
79
80
Parameters:
81
- document: Document to normalize (dict)
82
- schema: Override schema for normalization (dict, optional)
83
- always_return_document: Return document even if validation fails (bool)
84
85
Returns:
86
dict or None: Normalized document, or None if normalization failed
87
"""
88
```
89
90
### Properties and State
91
92
Access to validator state and configuration.
93
94
```python { .api }
95
# Schema and Configuration
96
@property
97
def schema(self) -> dict:
98
"""Current validation schema"""
99
100
@schema.setter
101
def schema(self, schema):
102
"""Set validation schema"""
103
104
@property
105
def allow_unknown(self) -> bool:
106
"""Whether unknown fields are allowed"""
107
108
@allow_unknown.setter
109
def allow_unknown(self, value):
110
"""Set allow_unknown behavior"""
111
112
@property
113
def require_all(self) -> bool:
114
"""Whether all schema fields are required"""
115
116
@require_all.setter
117
def require_all(self, value):
118
"""Set require_all behavior"""
119
120
@property
121
def ignore_none_values(self) -> bool:
122
"""Whether None values are ignored during validation"""
123
124
@ignore_none_values.setter
125
def ignore_none_values(self, value):
126
"""Set ignore_none_values behavior"""
127
128
@property
129
def purge_unknown(self) -> bool:
130
"""Whether unknown fields are removed"""
131
132
@purge_unknown.setter
133
def purge_unknown(self, value):
134
"""Set purge_unknown behavior"""
135
136
@property
137
def purge_readonly(self) -> bool:
138
"""Whether readonly fields are removed during normalization"""
139
140
@purge_readonly.setter
141
def purge_readonly(self, value):
142
"""Set purge_readonly behavior"""
143
144
# Validation State
145
@property
146
def document(self) -> dict:
147
"""The document being/recently processed"""
148
149
@property
150
def errors(self):
151
"""Formatted validation errors from last operation"""
152
153
@property
154
def document_error_tree(self):
155
"""Errors organized by document structure"""
156
157
@property
158
def schema_error_tree(self):
159
"""Errors organized by schema structure"""
160
161
@property
162
def recent_error(self):
163
"""Most recent individual validation error"""
164
165
# Context Properties
166
@property
167
def is_child(self) -> bool:
168
"""True if this is a child validator"""
169
170
@property
171
def document_path(self) -> tuple:
172
"""Current path within document during validation"""
173
174
@property
175
def schema_path(self) -> tuple:
176
"""Current path within schema during validation"""
177
178
@property
179
def root_document(self):
180
"""Root validator's document"""
181
182
@property
183
def root_schema(self):
184
"""Root validator's schema"""
185
186
@property
187
def root_allow_unknown(self):
188
"""Root validator's allow_unknown setting"""
189
190
@property
191
def root_require_all(self):
192
"""Root validator's require_all setting"""
193
```
194
195
### Registry Integration
196
197
Integration with schema and rules registries.
198
199
```python { .api }
200
@property
201
def schema_registry(self):
202
"""Schema registry instance"""
203
204
@schema_registry.setter
205
def schema_registry(self, registry):
206
"""Set schema registry"""
207
208
@property
209
def rules_set_registry(self):
210
"""Rules set registry instance"""
211
212
@rules_set_registry.setter
213
def rules_set_registry(self, registry):
214
"""Set rules set registry"""
215
```
216
217
### Error Handler Integration
218
219
Error handling customization.
220
221
```python { .api }
222
@property
223
def error_handler(self):
224
"""Current error handler instance"""
225
```
226
227
### Cache Management
228
229
Schema validation cache management.
230
231
```python { .api }
232
@classmethod
233
def clear_caches(cls):
234
"""Clear schema validation cache"""
235
```
236
237
### Introspection Properties
238
239
Access to available validation rules and capabilities.
240
241
```python { .api }
242
@property
243
def types(self):
244
"""Available type constraints mapping"""
245
246
@property
247
def validators(self):
248
"""Available validator methods"""
249
250
@property
251
def coercers(self):
252
"""Available coercion methods"""
253
254
@property
255
def default_setters(self):
256
"""Available default setter methods"""
257
258
@property
259
def rules(self):
260
"""Available validation rules"""
261
262
@property
263
def normalization_rules(self):
264
"""Rules applied during normalization"""
265
266
@property
267
def validation_rules(self):
268
"""Rules applied during validation"""
269
270
types_mapping: dict
271
"""Type names to TypeDefinition mapping (class attribute)"""
272
273
checkers: tuple
274
"""Available check_with methods (class attribute)"""
275
```
276
277
### Class Attributes
278
279
Configuration of validation behavior.
280
281
```python { .api }
282
mandatory_validations: tuple
283
"""Rules evaluated on every field"""
284
285
priority_validations: tuple
286
"""Rules processed first during validation"""
287
```
288
289
## Usage Examples
290
291
### Basic Validation
292
293
```python
294
from cerberus import Validator
295
296
# Create validator with schema
297
schema = {
298
'name': {'type': 'string', 'minlength': 2, 'maxlength': 50},
299
'age': {'type': 'integer', 'min': 0, 'max': 150},
300
'email': {'type': 'string', 'regex': r'^[^@]+@[^@]+\.[^@]+$'}
301
}
302
303
v = Validator(schema)
304
305
# Valid document
306
document = {
307
'name': 'John Doe',
308
'age': 30,
309
'email': 'john@example.com'
310
}
311
312
if v.validate(document):
313
print("Document is valid!")
314
else:
315
print("Validation errors:", v.errors)
316
```
317
318
### Validation with Options
319
320
```python
321
from cerberus import Validator
322
323
schema = {'name': {'type': 'string'}}
324
325
# Allow unknown fields
326
v = Validator(schema, allow_unknown=True)
327
v.validate({'name': 'John', 'extra': 'value'}) # True
328
329
# Require all schema fields
330
v = Validator(schema, require_all=True)
331
v.validate({'name': 'John'}) # True
332
v.validate({}) # False - missing required field
333
334
# Purge unknown fields
335
v = Validator(schema, purge_unknown=True)
336
doc = {'name': 'John', 'extra': 'value'}
337
normalized = v.normalized(doc) # {'name': 'John'}
338
```
339
340
### Update Validation
341
342
```python
343
from cerberus import Validator
344
345
schema = {
346
'name': {'type': 'string', 'required': True},
347
'age': {'type': 'integer', 'required': True}
348
}
349
350
v = Validator(schema)
351
352
# Partial update - only validate provided fields
353
update = {'age': 25}
354
v.validate(update, update=True) # True - name not required for updates
355
```
356
357
### Callable Interface
358
359
```python
360
from cerberus import Validator
361
362
v = Validator({'name': {'type': 'string'}})
363
364
# Use validator as callable
365
result = v({'name': 'John'}) # True
366
result = v({'name': 123}) # False
367
```
368
369
## Exception Classes
370
371
```python { .api }
372
class DocumentError(Exception):
373
"""Raised when target document is missing or has wrong format"""
374
```
375
376
This exception is raised when the document being validated is not in the expected format (typically when it's not a dictionary) or is missing entirely.