Skip to content

Latest commit

 

History

History
27 lines (19 loc) · 747 Bytes

20240710135538.md

File metadata and controls

27 lines (19 loc) · 747 Bytes

Write a custom validator in Pydantic

You can use the field_validator decorator.

Here we check if the signup date is not in the future for example:

from datetime import date, timedelta

from pydantic import BaseModel, Field, field_validator

class User(BaseModel):
    username: str = Field(..., min_length=3, max_length=10)
    signup_date: date

    @field_validator('signup_date')
    def check_date_not_in_future(cls, v):
        if v > date.today():
            raise ValueError('signup_date cannot be in the future')
        return v

User(username="pybob", signup_date=date.today())  # ok
# ValidationError... signup_date cannot be in the future
User(username="pybob", signup_date=date.today() + timedelta(days=1))

#pydantic