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 pageshowhide
explore
- Zod31 questions
- Primitive Schemas5 questions
- Parsing at the Boundary4 questions
- Schema-Derived Types5 questions
- Object and Array Composition5 questions
- Refinements and Transforms6 questions
- Issue Formatting & Messages6 questions
- Pydantic35 questions
- Models and Fields6 questions
- Validators5 questions
- Strict vs Lax Coercion6 questions
- Dumping & Serializers6 questions
- Settings Management6 questions
- V1 to V2 Migration6 questions
- FluentValidation6 questions
questions
72 · 3 sectionsIn Zod 4, what does the ZodError from a failed safeParse contain, and what do each issue's code, path and message tell you?
basics
~20 sA 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.
In Zod 4, what happens when schema.parse() and schema.safeParse() receive invalid input, and how do you read each result?
basics
~20 sZod'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.
In Zod 4, what do z.string(), z.number() and z.literal() accept, and why does z.number() reject the string "42"?
basics
~10 sZod 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.
In Zod 4, what is the difference between adding .refine() and adding .transform() to a schema?
basics
~20 sIn 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.
In Zod 4, how do you get a TypeScript type from a schema with z.infer, and why does the call need typeof?
basics
~20 sDeclare 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.
In Pydantic 2, how do required, optional and defaulted fields differ on a BaseModel, and does `X | None` make a field optional?
basics
~20 sIn 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.
In Pydantic 2, how do model_dump(), model_dump(mode='json') and model_dump_json() differ, and when would you use each?
basics
~10 sIn 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.
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?
basics
~20 sInstantiating 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.
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?
basics
~10 sPydantic 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.
In Pydantic 2, what should a custom validator raise to reject a value, and what does the resulting ValidationError contain?
basics
~10 sA 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.
With FluentValidation, how do you write a validator for a create-order command, and how do NotNull and NotEmpty differ?
basics
~10 sInherit 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.
With FluentValidation, how do you validate a create-order command's nested shipping address and every item in its line-item list?
basics
~20 sAttach 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.
With FluentValidation, how do you write order rules that depend on another property, using When, Unless, Must or Custom?
basics
~20 sWhen 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.
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?
basics
~20 sThe 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.
In FluentValidation 12, what do Cascade(CascadeMode.Stop), RuleLevelCascadeMode and ClassLevelCascadeMode each stop, and what replaced StopOnFirstFailure?
basics
~20 sBoth 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.