Sub topic 2
Validating Data with `parse` and `safeParse`
Assume you know basic TypeScript types, JavaScript objects, JSON, npm imports, and try/catch. Zod validates unknown runtime data and returns data that matches a schema.
Choosing `parse` or `safeParse`
parse returns validated data. If validation fails, it throws a ZodError, so use it when invalid input should stop the current operation.
safeParse never throws for validation failures. It returns either { success: true, data } or { success: false, error }. This is useful for HTTP handlers and forms, where invalid input is an expected result.
import { z } from "zod";
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
});
const value: unknown = JSON.parse('{"id": 1, "name": "Ada"}');
try {
const user = User.parse(value);
console.log(user.name);
} catch (error) {
if (error instanceof z.ZodError) {
console.error(error.issues);
}
}
const result = User.safeParse(value);
if (result.success) {
console.log(result.data.id);
} else {
console.error(result.error.issues);
}Reading validation errors
Each item in error.issues describes one failure. Its path identifies the field, and its message explains the problem.
const result = User.safeParse({ id: "wrong", name: "" });
if (!result.success) {
for (const issue of result.error.issues) {
console.error(issue.path.join("."), issue.message);
}
}Keep these messages for logs or convert them into field-level messages for a form. Do not trust the original input until parsing succeeds.
Optional, nullable, and default fields
optional()allows the property to be missing orundefined.nullable()allows the valuenull, but the property must still exist.default()supplies a value when the input isundefined.
const Settings = z.object({
nickname: z.string().optional(),
avatarUrl: z.string().nullable(),
theme: z.enum(["light", "dark"]).default("light"),
});
Settings.parse({ avatarUrl: null }); // theme becomes "light"Collections
Use array for a list, tuple for a fixed-length positional structure, record for string-keyed values, and enum for a limited set of strings.
const Scores = z.array(z.number().min(0));
const Point = z.tuple([z.number(), z.number()]);
const Labels = z.record(z.string(), z.string());
const Role = z.enum(["admin", "member", "guest"]);These schemas reject incorrect element types as well as incorrect container shapes.
Exercise
Which method should a form handler use when invalid input should produce field errors instead of throwing?
Show answer
Use safeParse, then inspect result.error.issues when success is false.