Sobes.tech
Junior — Middle

Explain the role and purpose of a validator in the Pydantic library.

sobes.tech AI

Answer from AI

In Pydantic, a validator is a method that checks and transforms data when creating models.

It allows:

  • Validating the correctness of input data (e.g., format, value range).
  • Transforming data (e.g., string to date).
  • Adding custom validation logic.

Example of a validator in Pydantic:

from pydantic import BaseModel, validator

class User(BaseModel):
    name: str
    age: int

    @validator('age')
    def age_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Age must be positive')
        return v

Here, the age_must_be_positive method checks that the age is greater than zero and raises an error if not.