Discover how a simple decorator can save you hours of debugging and messy code!
Why Custom validation with validator decorator in FastAPI? - Purpose & Use Cases
Imagine you have a form where users enter their birthdate, and you want to check if they are at least 18 years old. You write code everywhere to check this manually for every input.
Manually checking validation in many places leads to repeated code, mistakes, and inconsistent rules. It's easy to forget a check or write it differently each time.
The validator decorator lets you write validation logic once inside your data model. FastAPI runs it automatically whenever data is received, keeping your code clean and consistent.
if user.birthdate > today - timedelta(days=18*365): raise ValueError('Must be 18 or older')
@validator('birthdate') def check_age(cls, v): from datetime import datetime, timedelta today = datetime.today().date() if v > today - timedelta(days=18*365): raise ValueError('Must be 18 or older') return v
This makes your app safer and easier to maintain by centralizing all validation rules in one place.
When building a signup form, you can ensure all user inputs meet your rules without repeating checks in every route or function.
Manual validation is repetitive and error-prone.
The validator decorator centralizes validation logic.
This leads to cleaner, safer, and more maintainable code.