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.

TypescriptForm Validation

Code

typescriptsnippet
22 lines
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: zod is a real dependency, resolved by the package manager.
  • The parsed.success check ends the failure path with an early return, 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

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.