skip to content

Validation Libraries

Libraries that parse untrusted data at the boundary into typed values the rest of the app can trust: Zod, Pydantic and FluentValidation. Asked where security, types and error messages meet.

on this pageshow

explore

questions

72 · 3 sections

In Zod 4, what does the ZodError from a failed safeParse contain, and what do each issue's code, path and message tell you?

level: juniorimportance: must knowfreq 62%
basics
~20 s

A Zod 4 ZodError holds an issues array, one entry per problem. Each issue carries a code naming the kind of failure, a path locating the bad value from the root, a human message, and code-specific fields such as expected or minimum.

open as a page

In Zod 4, what happens when schema.parse() and schema.safeParse() receive invalid input, and how do you read each result?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Zod's parse() returns the typed value or throws a ZodError when input fails the schema. safeParse() does not throw on invalid input; it returns { success: true, data } or { success: false, error } holding a ZodError.

open as a page

In Zod 4, what do z.string(), z.number() and z.literal() accept, and why does z.number() reject the string "42"?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Zod 4's scalar schemas check the runtime type without converting: z.string() takes strings, z.number() finite numbers, z.literal() its exact values. "42" is a string, so z.number() rejects it; conversion is opt-in through z.coerce.

open as a page

In Zod 4, what is the difference between adding .refine() and adding .transform() to a schema?

level: juniorimportance: must knowfreq 60%
basics
~20 s

In Zod 4, .refine() adds a custom check: its function returns truthy or falsy, the value passes through unchanged, and a falsy result records an issue with code custom. .transform() replaces the validated value with whatever its function returns.

open as a page

In Zod 4, how do you get a TypeScript type from a schema with z.infer, and why does the call need typeof?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Declare the schema as a value, then write type User = z.infer<typeof User>. The typeof is needed because the schema is a runtime object, and z.infer reads the parsed-output type that Zod attaches to it.

open as a page

In Pydantic 2, how do required, optional and defaulted fields differ on a BaseModel, and does `X | None` make a field optional?

level: juniorimportance: must knowfreq 75%
basics
~20 s

In Pydantic 2 a field is required unless it has a default. note: str | None is still required but accepts None; only note: str | None = None may be omitted. Version 1 gave Optional fields an implicit None default.

open as a page

In Pydantic 2, how do model_dump(), model_dump(mode='json') and model_dump_json() differ, and when would you use each?

level: juniorimportance: must knowfreq 74%
basics
~10 s

In Pydantic 2, model_dump() returns a dict that keeps Python values such as datetime, Decimal and tuples; model_dump(mode='json') returns a dict of JSON-safe values; model_dump_json() returns the encoded JSON string itself.

open as a page

In Pydantic 2, how does a pydantic-settings BaseSettings class fill its fields from environment variables, and what happens when a required one is missing?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Instantiating a BaseSettings subclass reads every field not passed as a keyword argument from an environment variable named after the field, matched case-insensitively, and validates it by type; a missing required field raises ValidationError on the spot.

open as a page

In Pydantic 2, what replaced the version 1 model methods parse_obj, parse_raw, dict, json and from_orm, and do the old names still work?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Pydantic 2 put the model API under a model_ prefix: parse_obj became model_validate, parse_raw model_validate_json, dict and json model_dump and model_dump_json, and from_orm model_validate with from_attributes. Old names remain as warning shims.

open as a page

In Pydantic 2, what should a custom validator raise to reject a value, and what does the resulting ValidationError contain?

level: juniorimportance: must knowfreq 66%
basics
~10 s

A Pydantic 2 validator should raise ValueError (or PydanticCustomError); Pydantic collects it with other failures into one ValidationError whose errors() list gives each problem's type, loc, msg and input.

open as a page

With FluentValidation, how do you write a validator for a create-order command, and how do NotNull and NotEmpty differ?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Inherit AbstractValidator<CreateOrderCommand>, declare RuleFor chains in its constructor and call Validate to get a ValidationResult. NotNull rejects only null; NotEmpty also rejects whitespace strings, empty collections and a value type's default, such as 0.

open as a page

With FluentValidation, how do you validate a create-order command's nested shipping address and every item in its line-item list?

level: middleimportance: must knowfreq 60%
basics
~20 s

Attach an AddressValidator with SetValidator (or inline ChildRules) for the shipping address, and use RuleForEach with SetValidator or ChildRules for line items. Null children and null lists are skipped, so add NotNull; failures carry paths like LineItems[1].Quantity.

open as a page

With FluentValidation, how do you write order rules that depend on another property, using When, Unless, Must or Custom?

level: middleimportance: should knowfreq 55%
basics
~20 s

When and Unless decide whether a rule runs; a trailing When covers every validator before it in the chain. Must with the root object, or a comparison validator taking a lambda, checks one field against another; Custom adds several failures.

open as a page

With FluentValidation, an order validator with a MustAsync rule passes its TestValidate unit tests yet throws in production. Why, and how should it be tested?

level: seniorimportance: should knowfreq 40%
basics
~20 s

The synchronous path throws only once execution reaches an async rule. Tests that stop earlier, at a failing cascade, a false When or a null child, never reach MustAsync, but a valid production order does. Call ValidateAsync everywhere and test with TestValidateAsync, including a valid case.

open as a page

In FluentValidation 12, what do Cascade(CascadeMode.Stop), RuleLevelCascadeMode and ClassLevelCascadeMode each stop, and what replaced StopOnFirstFailure?

level: seniorimportance: should knowfreq 45%
basics
~20 s

Both levels default to Continue. Rule level, set by Cascade(CascadeMode.Stop) or RuleLevelCascadeMode, skips a chain's later validators after one fails. Class level, ClassLevelCascadeMode, ends the run after the first failing rule. FluentValidation 12 removed StopOnFirstFailure.

open as a page