Pydantic Field Validator Coercion
Normalize messy form input with Pydantic field validators, trimming strings, coercing digit strings, and rejecting malformed values early.
Code
from typing import Annotated
from pydantic import BaseModel, Field, field_validator, model_validator
class SignupForm(BaseModel):
email: Annotated[str, Field(min_length=5, max_length=120)]
age: Annotated[int, Field(ge=18, le=120)]
zipcode: str
password: str
password_confirm: str
@field_validator('email', mode='before')
@classmethod
def normalize_email(cls, raw: object) -> object:
if isinstance(raw, str):
candidate = raw.strip().lower()
if candidate.startswith('mailto:'):
candidate = candidate.removeprefix('mailto:')
return candidate
return raw
@field_validator('zipcode', mode='before')
@classmethod
def digits_only(cls, raw: object) -> object:
if isinstance(raw, str) and raw.isdigit() and len(raw) == 5:
return raw
raise ValueError('zipcode must be exactly 5 digits')
@model_validator(mode='after')
def passwords_match(self) -> 'SignupForm':
if self.password != self.password_confirm:
raise ValueError('passwords do not match')
return self
form = SignupForm(
email=' MAILTO:Ada@Example.COM ',
age='30',
zipcode='02138',
password='hunter2xx',
password_confirm='hunter2xx',
)
print('normalized email:', form.email, 'age type:', type(form.age).__name__)How the snippet works
Pydantic Field Validator Coercion keeps everything in the class SignupForm and the functions normalize_email, digits_only and passwords_match.
Reach for pydantic and what you get is Annotated, BaseModel, Field, field_validator, model_validator — that is the whole API contact area. Invalid states are rejected up front: it throws ValueError instead of continuing with bad data.
Caveats
- Plan for an install step:
pydanticis a real dependency, resolved by the package manager. - The guard
self.password != self.password_confirmshort-circuits the flow with an earlyraisewhen its condition holds.
Using it
Entry signature: def normalize_email(cls, raw: object) -> object
Output lines are prefixed (normalized email:), making each step’s effect easy to spot.
normalize_email is what another module would consume; nothing else here is load-bearing for callers.
Key statements
def normalize_email(cls, raw: object) -> object:
if isinstance(raw, str):
candidate = raw.strip().lower()
if candidate.startswith('mailto:'):
candidate = candidate.removeprefix('mailto:')
return candidate
return raw
def digits_only(cls, raw: object) -> object:
if isinstance(raw, str) and raw.isdigit() and len(raw) == 5:
return raw
raise ValueError('zipcode must be exactly 5 digits')
def passwords_match(self) -> 'SignupForm':
if self.password != self.password_confirm:
raise ValueError('passwords do not match')
return self
Interactive Tools for This Topic
FAQ
- What does the snippet do with malformed data?
- `ValueError` is raised at the guard (`self.password != self.password_confirm`), so invalid state never reaches the main logic.
- What does this need from the package registry?
- These are real dependencies: `pydantic`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.