Normalize input before type validation
A before validator receives the raw input, so it can normalize one explicitly supported representation before Pydantic checks the annotated type. It must handle unexpected types rather than assuming every input is already a string.
Keep normalization narrow. Removing whitespace from a name is reasonable; silently converting every object to text can hide a caller error. Return unsupported inputs unchanged when you want normal type validation to explain them. This keeps conversion policy separate from the model's ordinary type and field constraints.
from pydantic import BaseModel
from pydantic import field_validator
class Tag(BaseModel):
name: str
@field_validator("name", mode="before")
@classmethod
def strip(cls, value):
if isinstance(value, str):
return value.strip()
return value
print(Tag(name=" tea ").name)Your task
Implement clean_name(raw) validating a Person model. Strip whitespace from the string name before checking its minimum length of 1. Reject nonstrings and whitespace-only names.
The explanation opens here once every check passes.