Sub topic 6
Reading and reporting validation errors
This chapter assumes you can use safeParse from the previous chapter and can read a TypeScript type. You should also know the difference between an exception and a returned result. After this chapter you will be able to read a Zod error, turn it into messages a user or another program can use, and avoid a few common mistakes.
What a failed parse gives you
When validation fails, Zod produces a ZodError. Its main property is issues, an array with one entry for each rule the data broke. parse throws the error. safeParse returns it as result.error.
Zod does not stop at the first problem. For an object, it checks every field and reports every failure it finds. A user who submits a form with three mistakes can see all three at once.
Each entry in issues has these properties:
| Property | Type | Meaning |
|---|---|---|
| `path` | array of keys and indexes | Where the bad value sits inside the input, for example `["items", 0, "qty"]`. |
| `message` | string | A human-readable explanation. |
| `code` | string | A machine-readable category, such as `invalid_type` or `too_small`. |
Some issues carry extra detail that depends on the code. A too_small issue, for example, includes the minimum that was violated. The exact extra properties and the default message wording differ between Zod 3 and Zod 4. Rely on path, message, and code, which exist in both. Do not compare against default message text.
A schema with nested errors
The following schema has a nested object and an array of objects. The input breaks several rules at once.
import { z } from "zod";
const Order = z.object({
id: z.number().int(),
customer: z.object({
email: z.string().email("Enter a valid email address"),
}),
items: z
.array(
z.object({
sku: z.string().min(1, "SKU is required"),
qty: z.number().int().positive(),
})
)
.min(1, "An order needs at least one item"),
});
const input = {
id: 1.5,
customer: { email: "nope" },
items: [
{ sku: "", qty: 0 },
{ sku: "A1", qty: "2" },
],
};
const result = Order.safeParse(input);
if (!result.success) {
for (const issue of result.error.issues) {
console.log(issue.path.map(String).join("."), "|", issue.code, "|", issue.message);
}
}The loop prints one line per problem. The paths are id, customer.email, items.0.sku, items.0.qty, and items.1.qty. The path of each issue leads from the root of the input to the offending value. Array positions appear as numbers, so items.1.qty means the qty field of the second item.
The last issue is a type failure. The string "2" is not a number, and safeParse does not convert it. Coercion is covered in a later chapter.
Custom messages
Every built-in check accepts a message as its last argument. In the example above, "SKU is required" replaces the default text for the min(1) check. Write messages for the person who will read them. "Enter a valid email address" tells a user what to do, while a default message describes the failed rule.
Messages are the only part of an issue you should show to users directly. The code and path are for your own logic, such as choosing which form field to highlight.
When a check does not run
Zod runs checks in layers, and a later layer is skipped when an earlier one fails. This affects what you see in issues.
- If a value has the wrong type, the checks for that type do not run. A number given to
z.string().min(1)produces oneinvalid_typeissue and notoo_smallissue. - Checks on the same valid type, such as
minandemailon one string, usually all run. A short, malformed string can therefore produce two issues for the same path. - A cross-field
refineon an object typically does not run while individual fields are invalid. A user who enters a short password and a mismatched confirmation may see only the length error first. The mismatch error appears after they fix the length.
Expect this layering, and do not treat it as a bug. If your interface must show every problem at once, move the cross-field rule into a place where it does not depend on the other fields passing, or accept the two-step experience.
Grouping issues by field
A flat list is awkward for a form, where each input needs its own messages. Build a lookup from the paths.
import { z } from "zod";
function toFieldErrors(error: z.ZodError): Record<string, string[]> {
const out: Record<string, string[]> = {};
for (const issue of error.issues) {
const key = issue.path.map(String).join(".") || "_root";
(out[key] ??= []).push(issue.message);
}
return out;
}The "_root" key covers an issue whose path is empty. That happens when the whole input has the wrong type, for example when someone sends null instead of an object.
Zod also ships its own helpers for this. In Zod 3, error.flatten() returns { formErrors, fieldErrors }, where fieldErrors maps top-level field names to message arrays. In Zod 4 the same idea is z.flattenError(error), and z.treeifyError(error) gives a nested structure that mirrors the input. The flatten helpers only group by the first path segment, so a nested failure such as customer.email is filed under customer. A hand-written helper like toFieldErrors gives you full paths, and it behaves the same in every version.
parse and ZodError
parse throws the same ZodError, so you can catch it and read the same issues.
import { z } from "zod";
const Name = z.object({ name: z.string().min(1, "Name is required") });
function readName(text: string): string | null {
try {
return Name.parse(JSON.parse(text)).name;
} catch (err) {
if (err instanceof z.ZodError) {
console.error("Invalid data:", err.issues.map((i) => i.message));
} else if (err instanceof SyntaxError) {
console.error("Not valid JSON");
} else {
throw err;
}
return null;
}
}Note the three branches. JSON.parse throws a SyntaxError when the text is not JSON at all, and that failure comes before Zod sees any data. A ZodError means the text was valid JSON with the wrong shape. Anything else is an unexpected failure, so the code rethrows it. A blanket catch that treats every exception as a validation failure hides real bugs.
Reporting errors from an API
At an application boundary, return a stable structure that clients can rely on. This function wraps a schema and returns either typed data or a ready-to-send error.
import { z } from "zod";
type Validated<T> =
| { ok: true; data: T }
| { ok: false; status: 400; errors: Record<string, string[]> };
function validate<S extends z.ZodTypeAny>(
schema: S,
input: unknown
): Validated<z.output<S>> {
const result = schema.safeParse(input);
if (result.success) {
return { ok: true, data: result.data };
}
const errors: Record<string, string[]> = {};
for (const issue of result.error.issues) {
const key = issue.path.map(String).join(".") || "_root";
(errors[key] ??= []).push(issue.message);
}
return { ok: false, status: 400, errors };
}
const Login = z.object({
email: z.string().email("Enter a valid email address"),
password: z.string().min(8, "Use at least 8 characters"),
});
const outcome = validate(Login, { email: "[email protected]", password: "short" });
if (!outcome.ok) {
console.log(outcome.status, JSON.stringify(outcome.errors));
// 400 {"password":["Use at least 8 characters"]}
}The return type is a discriminated union on ok, so TypeScript narrows to data or errors after you check it. The output is the same structure on every endpoint. Clients can write one error handler for all of them.
Common mistakes
- Showing raw
ZodErrortext to users. Its string form is a JSON dump of the issues. Map issues to your own messages instead. - Logging whole inputs. Passwords and tokens end up in logs. Log the
pathandcodeof each issue, which locate the problem without copying the data. - Branching on message text. Default messages change between versions. Branch on
codeandpath. - Using
parsewhere failure is expected. User input is wrong often. UsesafeParsethere and keepparsefor data that should always be valid, such as configuration at startup. - Ignoring numeric path segments. Code that assumes every path segment is a field name breaks on array indexes. Treat segments as
string | number(or symbols in Zod 4).
Exercise
A schema is z.object({ tags: z.array(z.string().min(1)) }). The input is { tags: ["ok", "", 5] }. What path values do the issues have, and which code does each one most likely carry?
Show answer
There are two issues. The empty string at index 1 has path ["tags", 1] and code too_small, because it breaks min(1). The number at index 2 has path ["tags", 2] and code invalid_type, because a number is not a string. Both are reported together, since Zod checks every array element and does not stop at the first failure.
Exercise
Why does issue.path.map(String).join(".") produce "items.0.qty" for the path ["items", 0, "qty"], and why is it preferable to issue.path.join(".") in code that must work across Zod versions?
Show answer
map(String) converts each segment, including the number 0, to a string, and join(".") then joins them with dots. Plain join works for strings and numbers, but in Zod 4 a path can contain symbols, and join throws a TypeError on a symbol. Mapping through String handles symbols safely.