Sub topic 5
Validating Data with `parse` and `safeParse`
Assume you know basic TypeScript types, JavaScript objects and JSON, npm imports, and try/catch. This chapter focuses on choosing a validation method after you have defined a Zod schema.
TypeScript checks source code during compilation. It does not check values received from an HTTP request, file, or database while the program runs. Treat those values as unknown until a schema validates them.
`parse`: return a value or throw
parse validates a value and returns the parsed result when validation succeeds. When validation fails, it throws a ZodError.
Use parse when invalid data should stop the current operation and your surrounding code already handles exceptions. A common example is application startup. If required configuration is invalid, continuing may be unsafe.
import { z } from "zod";
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
});
const input: unknown = {
id: 7,
name: "Mina",
};
try {
const user = User.parse(input);
console.log(`Loaded ${user.name} with ID ${user.id}`);
} catch (error) {
if (error instanceof z.ZodError) {
console.error(error.issues);
} else {
throw error;
}
}The result is typed according to the schema. Before calling parse, input is unknown. After a successful call, user has the inferred object type.
parse does not make malformed JSON safe by itself. JSON.parse runs first and can throw its own SyntaxError. If you receive JSON text, handle decoding and schema validation as separate steps.
`safeParse`: inspect the result
safeParse never throws for an ordinary validation failure. It returns a discriminated result object:
- On success,
successistrueanddatacontains the validated value. - On failure,
successisfalseanderrorcontains aZodError.
This approach fits request handlers and forms, where invalid input is expected and should produce a normal response.
const input: unknown = {
id: "seven",
name: "",
};
const result = User.safeParse(input);
if (result.success) {
console.log(result.data.name);
} else {
for (const issue of result.error.issues) {
console.error(issue.path.join("."), issue.message);
}
}TypeScript narrows result after the if check. Do not read result.data before checking result.success.
| Method | Failure behavior | Useful when |
|---|---|---|
| `parse` | Throws `ZodError` | Invalid data should interrupt the operation |
| `safeParse` | Returns `{ success: false, error }` | Invalid data is an expected user or client error |
Choosing between the methods
Avoid replacing validation with a type assertion such as input as User. An assertion changes what TypeScript believes, but it performs no runtime check. Also avoid catching every error and returning “invalid input.” A programming error or database failure is different from a failed schema check.
For asynchronous refinements, use parseAsync or safeParseAsync and await the result. The synchronous methods cannot run asynchronous validation rules.
Exercise
Which method should a form handler usually use, and where should it read the validation messages?
Show answer
It should usually use safeParse. When success is false, it should read messages from result.error.issues.