Boundary validation
Validate request bodies, form values, or configuration objects while handling invalid input through normal branching.
Zod · Module
Zod's safeParse method validates input without throwing for validation failures. It returns a discriminated result containing either parsed data or a ZodError.
Call safeParse on a Zod schema with unknown input. It returns a discriminated result object: test success to access validated data, or access the ZodError when validation fails. For asynchronous refinements or transforms, use safeParseAsync instead.
schema.safeParse(data: unknown)| Name | Type | Description |
|---|---|---|
data | unknown | The unknown value to validate against the schema. |
A discriminated union: { success: true; data: T } or { success: false; error: ZodError }.
import { z } from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
const result = Player.safeParse({ username: "billie", xp: 100 });
if (result.success) {
console.log(result.data.username);
} else {
console.error(result.error);
}Checks the input without throwing: successful validation exposes parsed data, while failure exposes the validation error.
Validate request bodies, form values, or configuration objects while handling invalid input through normal branching.
Process user-provided data where rejected values should produce structured feedback instead of an exception.
Use the success flag to route valid and invalid values into separate typed control-flow branches.
safeParse validates input without requiring a try/catch for expected validation failures. It returns either a success result containing data or a failure result containing a ZodError.
Follow-up: How should asynchronous schema logic be handled? Use safeParseAsync when asynchronous refinements or transforms are present.
The result is a discriminated union. Check result.success first; the true branch provides result.data, while the false branch provides result.error.
Follow-up: What makes this narrowing reliable? The success property distinguishes the two result shapes and lets TypeScript narrow each branch.
safeParse is suitable when validation failure is expected and should be represented as ordinary control flow. A successful result contains the parsed value, and an unsuccessful result contains detailed validation information in a ZodError.
Follow-up: What is the asynchronous counterpart? safeParseAsync returns the analogous result for schemas using asynchronous APIs.
parsesafeParseAsyncZodError