MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Deploying AI into Production with FastAPI

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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
Edit dan Jalankan Kode