tezvyn:

Implement a custom validator for a single Pydantic model field

AI-drafted, machine-checkedSource: pydantic.devintermediate
Implement a custom validator for a single Pydantic model field
WHAT IT TESTS

Your grasp of Pydantic v2 field validation hooks.

ANSWER OUTLINE

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

RED FLAG

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

WHAT THIS TESTS: 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.

A GOOD ANSWER COVERS: 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.

COMMON WRONG ANSWERS: 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.

LIKELY FOLLOW-UPS: 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.

ONE 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.

Source: pydantic.dev

Read the original → pydantic.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.