Adding custom data validation with Pydantic
Up to now, we’ve seen how to apply basic validation to our models through 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 the field level or the object level.
Applying validation at the field level
This is the most common case: having a validation rule for a single field. To define a validation rule in Pydantic, we 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:
chapter04_custom_validation_01.py
from...