validator
- Python course
- Advanced
- Lesson 57/83
- 5 min
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 vThe 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 valueThe function can also transform the value; for example, it can lowercase a string and return it. This is useful to normalize data.
Practice 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).
Starter code
# bring in BaseModel and field_validator from pydantic
# define User class (name field)
# add a field_validator for name (length must be under 50)
# the validator takes cls and v, raises ValueError
# create a User instance and print the nameSample 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)Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the validator concepts
| Term | Meaning |
|---|---|
@field_validator |
Adds validation |
@classmethod |
Makes a class method |
cls |
Is the class reference |
ValueError |
Raises an error |
2 Which exception does the @field_validator function raise on failure?
- TypeError
- ValueError Correct answer
- IndexError
- KeyError
Explanation: ValueError is raised; Pydantic turns it into a validation error.
3 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
from pydantic import BaseModel, field_validator
class User(BaseModel):
name: str
@field_validator("name")
@classmethod
def short_name(cls, v):
return v
Explanation: @field_validator('name') adds field validation.