Skip to content
tezvyn:

Implement a custom validator for a single Pydantic model field

Source: pydantic.devMediumHow cards are made

Implement a custom validator for a single Pydantic model field
Summary

Your grasp of Pydantic v2 field validation hooks.

Key points

Use @field_validator as a classmethod, raise ValueError on failure, return the value.

Watch out for

Validating outside the model or confusing v1 @validator with v2.

What's really being asked

This question probes whether you know how to extend Pydantic v2 validation for a single field without breaking the model lifecycle. The interviewer wants to see that you understand the difference between ad-hoc field validation and reusable schema customization, and that you can articulate where validation logic belongs inside the model rather than in endpoint code.

The full answer

First, mention the @field_validator decorator applied to a classmethod that receives the raw value. Second, explain that the method should enforce the two rules by checking length with len(value) >= 10 and checking for a digit with any(c.isdigit() for c in value), raising a ValueError with a descriptive message if either check fails. Third, emphasize returning the value so Pydantic continues processing. Fourth, optionally note that if this password rule were needed across many models, you could build a reusable Annotated type using a frozen dataclass that implements __get_pydantic_core_schema__ and uses core_schema.no_info_wrap_validator_function to inject the logic into the schema, which is the pattern shown in the Pydantic docs for complex custom types.

The mistakes people make

A red flag is suggesting validation in the FastAPI endpoint or a manual helper before model instantiation, because that bypasses Pydantic's error aggregation and schema documentation. Another red flag is using Pydantic v1 @validator syntax without acknowledging the v2 migration to @field_validator and the classmethod requirement. A third red flag is mutating global state or performing expensive I/O like database lookups inside a field validator, since validators should be pure and fast.

What usually comes next

The interviewer may ask how you would return multiple distinct error messages rather than a single ValueError, which leads to Pydantic's ValidationError and error dict construction. They may also ask how to validate two fields together, which moves the discussion from @field_validator to @model_validator. Finally, they might ask how to expose this constraint in JSON Schema, which touches on customizing the core schema or using Field json_schema_extra.

A concrete example

You define a User model with password: str. Inside the model you write @field_validator('password') @classmethod def validate_password(cls, v: str) -> str: if len(v) < 10: raise ValueError('Password must be at least 10 characters'); if not any(ch.isdigit() for ch in v): raise ValueError('Password must contain at least one digit'); return v. When User(password='short') is instantiated, Pydantic raises a ValidationError with the exact message and location, which FastAPI will automatically convert into a 422 response with a detailed error body.

Interview question

You are writing a Pydantic v2 model with a name field that must be at least 3 characters. Which implementation is correct?

  • a.Run the length check in the FastAPI endpoint before creating the model.
  • b.Use @field_validator('name') on a classmethod that raises ValueError without returning the value.
  • c.Use @field_validator('name') on a classmethod that raises ValueError and returns the value.Correct
  • d.Use @validator('name') on an instance method that sets self.name after checking.
Why?

Pydantic v2 requires single-field validators to use @field_validator on a classmethod, raise ValueError on failure, and return the value so processing continues. Option B is tempting but wrong because omitting the return breaks the model lifecycle, and D uses the deprecated v1 pattern.

Just read this? Test yourself on what you have been reading.

Read the original → pydantic.dev

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on pydantic — each one lists the topics its interview covers.

See open roles