Get startedGet started for free

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 @validator decorator on email to check if the entered email ends with @mode360.com

These validators enhance security and system integration.

This exercise is part of the course

Deploying AI into Production with FastAPI

View Course

Exercise instructions

  • Add the Pydantic decorator to create a custom validator on the email field.
  • Use the string endswith method to check if the email address ends with the @mode360.com domain.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

from pydantic import BaseModel, 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
Edit and Run Code