Validation
56 bites tagged Validation — interview questions with model answers, and 60-second explainers.
Implement a custom validator for a single Pydantic model field
Use @field_validator as a classmethod, raise ValueError on failure, return the value. Your grasp of Pydantic v2 field validation hooks. Validating outside the model or confusing v1 @validator with v2.
Enforce positive price and SKU format using Pydantic Field without custom validators
Use Field(gt=0) for price and Field(pattern=r'^ITEM-\d{5}$') for SKU; mention Annotated. Pydantic V2 Field constraints vs custom validators. Suggesting @field_validator or conint/constr.
What is the difference between a Pydantic default and Optional field?
Both forms are non-required; str = 'guest' rejects None, Optional[str] = None accepts it. Separation of type constraints from requiredness.
How does Pydantic handle extra JSON fields, and how to configure it?
This tests Pydantic's data filtering behavior and configuration. By default, Pydantic ignores extra fields silently. Set model_config = ConfigDict(extra='forbid' or 'allow') to change it. A red flag is claiming FastAPI 422s by default on unknown fields.
How do you define a Pydantic model for FastAPI request body validation?
Subclass BaseModel with id int, email str, full_name str|None; pass it as a route param so FastAPI validates JSON and returns 422s. Schema validation via Python type hints. Saying manual request.json() parsing.
FastAPI non-integer query param default behavior
Tests FastAPI's automatic Pydantic validation and default error contracts. Strong answer: 422 Unprocessable Entity with JSON detail array containing loc, msg, and type fields. Red flag: saying 400 Bad Request or manual validation is needed.
How does FastAPI leverage Pydantic for request validation and serialization?
This tests your understanding of FastAPI's declarative validation. Explain that type hints trigger auto-parsing, Pydantic enforces schemas and errors, and return types auto-serialize responses. Red flag: manually parsing request.body() or json.loads in routes.
Per-Field Validation with @field_validator
@field_validator scrubs a single Pydantic field before it enters the model. Use it for rules like 'password must contain a digit' or 'port must exceed 1024'. It only sees one field at a time, so cross-field checks belong in a model validator instead.
express-validator: Validate at the Edge
express-validator stops garbage before it hits your logic. Use it on any route that accepts user input like form data, query strings, or JSON payloads. The biggest mistake is validating but forgetting to check validationResult, so invalid requests pass.
Model Risk Management: The Immune System for Production Models
Model Risk Management treats every deployed model as a liability that can silently decay. Banks use it to stop bad predictions from becoming bad decisions. The footgun is treating validation as a one-time checkbox instead of continuous governance.
Build and validate a login form with Form and GlobalKey
This tests Flutter's declarative form validation. A strong answer covers wrapping fields in a Form, using a GlobalKey<FormState>, calling validate on submit, and acting only on true.
Explain the validator property in TextFormField and what triggers error display
Tests Form validation lifecycle knowledge. Strong answer: validator returns String? error or null; formKey.currentState.validate() triggers all fields; returned string renders as inline error.
How do you prevent future leakage in time-series preprocessing?
This tests temporal causality in feature engineering and validation. Use only past data for lags and rolling windows and enforce a rolling validation split without shuffling. Red flags are random k-fold CV and global standardization leaking future information.
What client-side and server-side validations belong on a campaign sign-up form?
This tests defense in depth and UX trade-offs. A strong answer maps validations to layers: regex and immediate feedback client-side, strict schema and rate limiting server-side, plus duplicate checks. Red flag: claiming client-side validation is sufficient.
How would you implement specific error messages for failed validation rules?
Error codes from validators, a mapping layer separating logic from copy, and accessible inline rendering. Architecting validation as structured data instead of booleans.
What validation checks would you implement for an email field?
Tests your understanding of practical validation vs. theoretical purity. A great answer prioritizes user experience, uses simple syntax checks (like a single '@'), and relies on sending a verification email as the ultimate test.
How would you validate user-submitted email addresses at ingestion?
Tests your understanding of data validation beyond simple regex, focusing on robustness and system-level thinking. A good answer covers format checks, DNS/MX record validation, and blocking disposable services.
Zod: TypeScript-First Schema Validation
Zod creates a single source of truth for your data's shape, providing both runtime validation and static TypeScript type inference from one definition. Use it to parse API inputs or form data, ensuring data is correct and typed.
Angular Custom Validators: Beyond Built-in Rules
Custom validators let you define your own business logic for form inputs. Use them to check for unique usernames via an API or enforce complex password rules. The main footgun is forgetting async validators must return an Observable or Promise.
VeeValidate: Vue Forms Without the Boilerplate
VeeValidate manages the entire lifecycle of a Vue form—tracking values, validation, and submissions—so you don't write the state boilerplate. Use it for simple contact forms or complex wizards, especially with async validation. The footgun is mixing its APIs.
Angular's Built-in Form Validators
Angular's built-in validators are pre-made rules for your forms. Use them to easily check for required fields, min/max length, and valid email formats. The footgun is confusing `required` for text inputs with `requiredTrue`, which is only for checkboxes.
Zod: Validate Data, Infer Types
Zod acts as a bouncer for your data, validating it against a schema you define and inferring TypeScript types automatically. It's essential for validating API inputs or form submissions. The main footgun is forgetting to enable "strict": true in your tsconfig.
Pydantic: Reusable Validation with Annotated Types
Pydantic's `Annotated` attaches validation logic directly to a type, making it reusable. Define a custom type like `SquareNumber` once and apply it to any model field, ensuring consistent validation without repeating code.
FastAPI: Validating Models with Pydantic's Field
Pydantic's `Field` adds guardrails directly to your data model's attributes. Use it to enforce constraints like string length (`max_length=50`) or numeric ranges (`gt=0`), making your models self-validating.
Get Validation bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.