Adding custom validators
Mode360 Solutions is the organization behind the comment moderation system, and you're given a task to create a validation service for all employees. The system should be able to validate input details (username, email and age) such that only employees with an official email address can register.
You need to define a Pydantic User model using @field_validator decorator on email to check if the entered email ends with @mode360.com
These validators enhance security and system integration.
Bu egzersiz
Deploying AI into Production with FastAPI
kursunun bir parçasıdırEgzersiz talimatları
- Add the Pydantic decorator to create a custom validator on the
emailfield. - Use the string
endswithmethod to check if the email address ends with the@mode360.comdomain.
Uygulamalı interaktif egzersiz
Bu örnek kodu tamamlayarak bu egzersizi bitirin.
from pydantic import BaseModel, field_validator, Field
class User(BaseModel):
username: str = Field(..., min_length=5, max_length=20)
email: str
age: int
# Add the Pydantic decorator to validate
____('email')
def email_must_be_example_domain(cls, user_email):
# Use the endswith method to validate the email ends with @mode360.com
if not user_email.endswith("____"):
raise ValueError('Email must be from the mode360.com domain')
return user_email