Format Zod Errors Into Field Messages
Convert a Zod validation error into a keyed field-message map so a form can render every issue next to the input that caused it.
Code
import { z } from "zod";
export interface FieldErrors {
[field: string]: string[];
}
export function formatIssues(error: z.ZodError): FieldErrors {
const result: FieldErrors = {};
for (const issue of error.issues) {
const field = issue.path.length > 0 ? issue.path.join(".") : "_root";
(result[field] ??= []).push(issue.message);
}
return result;
}
export function validate<T extends z.ZodTypeAny>(schema: T, input: unknown) {
const parsed = schema.safeParse(input);
if (parsed.success) {
return { ok: true as const, data: parsed.data };
}
return { ok: false as const, errors: formatIssues(parsed.error) };
}Inside the code
Format Zod Errors Into Field Messages comes down to the functions formatIssues and validate.
Repetition is confined to for (const issue of error.issues) — the rest of the file is straight-line. z are the only symbols borrowed from zod — the coupling is explicit and narrow.
The result comes back as an object carrying const.
Points of care
- Plan for an install step:
zodis a real dependency, resolved by the package manager. - The
parsed.successcheck ends the failure path with an earlyreturn, handing back formatted issues instead of continuing.
Using it
What the module exports: export function formatIssues(error: z.ZodError)
formatIssues is the public entry point; everything else in the file exists to support it.
The call returns const.
Key statements
return { ok: false as const, errors: formatIssues(parsed.error) };
return { ok: true as const, data: parsed.data };
(result[field] ??= []).push(issue.message);
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does `formatIssues` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Do I need to install anything before running this?
- Yes: `zod` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.