Zod SafeParse Error Formatting
Validate untrusted payloads with Zod safeParse, aggregate every issue with paths, and flatten errors into field-keyed message maps.
Code
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.successcuts the flow short with an earlyreturnwhen 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
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 Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.XML FormatterRe-indent minified or messy XML into a readable structure, validating that every opening tag has a matching closing tag.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.