Get startedGet started for free

Field validation

You are building on the user comment moderation service. Your goal is to create a Pydantic User model that ensures data integrity across all users.

Implement validations for the username (min 5, max 50 characters) field.

Use Pydantic's Field class to add these constraints, and test your model with both valid and invalid product data to ensure it correctly handles various scenarios.

This exercise is part of the course

Deploying AI into Production with FastAPI

View Course

Exercise instructions

  • Import the base model and field classes from Pydantic.
  • Inherit Pydantic's base model in the User model.
  • Add field validations on username attribute in the User class to have at least 5 characters and no more than 20 characters.

Hands-on interactive exercise

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

# Import the base model and field validator from Pydantic
from pydantic import ____, ____

# Inherit Pydantic's base model
class User(____): 
    # Set minimum and maximum name length
    username: str = ____(..., ____=5, ____=20)
    email: str
    age: int

user = User(username="john_doe", email="[email protected]", age=25)
print(user)
Edit and Run Code