Zod SafeParse Error Formatting

Validate untrusted payloads with Zod safeParse, aggregate every issue with paths, and flatten errors into field-keyed message maps.

TypescriptData Integrity

Code

typescriptsnippet
28 lines
import { z } from 'zod';

const PayloadSchema = z.object({
  email: z.string().email(),
  age: z.number().int().min(18).max(120),
  tags: z.array(z.string().min(1)).max(5),
  role: z.enum(['admin', 'editor', 'viewer']).default('viewer'),
});

type Payload = z.infer<typeof PayloadSchema>;

function validate(raw: unknown):
  { ok: true; value: Payload } | { ok: false; fields: Record<string, string> } {
  const result = PayloadSchema.safeParse(raw);
  if (result.success) return { ok: true, value: result.data };

  const fields: Record<string, string> = {};
  for (const issue of result.error.issues) {
    const key = issue.path.join('.') || '_root';
    fields[key] ??= issue.message;
  }
  return { ok: false, fields };
}

const good = validate({ email: 'ada@example.com', age: 30, tags: ['a'] });
const bad = validate({ email: 'nope', age: 15, tags: [] });

console.log(good.ok, bad.ok ? '' : JSON.stringify(bad.fields));

How this snippet works

validate is the one function; PayloadSchema.safeParse feeds it.

A single loop drives the file — for (const issue of result.error.issues). The import line is the dependency contract: z comes from zod and nothing else.

The result comes back as an object carrying true.

What to watch for

  • Dependency check: zod — not built-in, must be present in the project.
  • The guard result.success cuts the flow short with an early return when its condition holds.

Applying it

Signature: function validate(raw: unknown)

The call returns true.

Statements that matter

if (result.success) return { ok: true, value: result.data };
fields[key] ??= issue.message;
return { ok: false, fields };

Interactive Tools for This Topic

FAQ

Does `validate` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Which packages must be installed first?
Yes. The imports resolve to `zod`, which the package manager must provide.