Custom validation with validator decorator in FastAPI
📖 Scenario: You are building a simple FastAPI app to register users. You want to make sure the user's username is at least 3 characters long and contains only letters and numbers.
🎯 Goal: Create a Pydantic model with a custom validator using the @validator decorator to check the username field. The validator should raise an error if the username is too short or contains invalid characters.
📋 What You'll Learn
Create a Pydantic model called
User with a username field of type str.Add a class method decorated with
@validator('username') to validate the username.The validator must check that
username is at least 3 characters long.The validator must check that
username contains only letters and numbers.Raise a
ValueError with a clear message if validation fails.💡 Why This Matters
🌍 Real World
Custom validation is essential in web APIs to ensure user input meets rules before saving or processing. This prevents errors and security issues.
💼 Career
Backend developers often write custom validators in FastAPI or similar frameworks to enforce business rules and data integrity.
Progress0 / 4 steps