Python
validator
Learn custom validation with @validator.
validator
@field_validator adds custom validation to a field. It is the recommended way in Pydantic v2, replacing the old @validator. The validation function takes the value, checks it and returns it.
from pydantic import BaseModel, field_validator
class User(BaseModel):
name: str
@field_validator("name")
@classmethod
def short_name(cls, v):
if len(v) > 50:
raise ValueError("too long")
return v
The function is marked with @classmethod; the first parameter is cls, the second is the value. To fail, raise ValueError.
Validation function
The validation function checks the value and returns it. On failure, ValueError is raised; Pydantic turns this into a validation error. Returning the value is required.
@field_validator("age")
@classmethod
def check_age(cls, v):
if v < 0:
raise ValueError("cannot be negative")
return v # return the value
The function can also transform the value; for example, it can lowercase a string and return it. This is useful to normalize data.
Exercise User model with custom validation
Start with from pydantic import BaseModel, field_validator. Define class User(BaseModel): with field name: str. With @field_validator("name") and @classmethod define def short_name(cls, v):. The function should do if len(v) > 50: raise ValueError("too long") and return v. Create an instance with u = User(name="Ayşe"). Print the name with print(u.name).
Show example solution
from pydantic import BaseModel, field_validator
class User(BaseModel):
name: str
@field_validator("name")
@classmethod
def short_name(cls, v):
if len(v) > 50:
raise ValueError("too long")
return v
u = User(name="Ayşe")
print(u.name)
Test yourself
-
Match the validator concepts
- @field_validator
- Adds validation
- @classmethod
- Makes a class method
- cls
- Is the class reference
- ValueError
- Raises an error
-
Which exception does the @field_validator function raise on failure?
- TypeError
- ValueError
- IndexError
- KeyError
Show answer
ValueError — ValueError is raised; Pydantic turns it into a validation error.
-
Complete the field_validator decorator
from pydantic import BaseModel, field_validator
class User(BaseModel):
name: str
@____("name")
@classmethod
def short_name(cls, v):
return v
Show answer
from pydantic import BaseModel, field_validator
class User(BaseModel):
name: str
@field_validator("name")
@classmethod
def short_name(cls, v):
return v
Next lesson: Config