Adding custom data validation with Pydantic
Up to now, we've seen how to apply basic validation to our models, through the Field
arguments or the custom types provided by Pydantic. In a real-world project, though, you'll probably need to add your own custom validation logic for your specific case. Pydantic allows this by defining validators, which are methods on the model that can be applied at a field level or an object level.
Applying validation at a field level
This is the most common case: have a validation rule for a single field. To define it in Pydantic, we'll just have to write a static method on our model and decorate it with the validator
decorator. As a reminder, decorators are syntactic sugar, allowing the wrapping of a function or a class with common logic, without compromising readability.
The following example checks a birth date by verifying that the person is not more than 120 years old:
chapter4_custom_validation_01.py
from datetime import...