Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Deploying AI into Production with FastAPI

Cursus bekijken

Oefeninstructies

  • 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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
Code bewerken en uitvoeren