Boundary validation
Validate request bodies, form submissions, or other untrusted values while keeping control flow explicit.
Zod · Function
safeParse validates data without throwing on validation failure. It returns either parsed data on success or a ZodError on failure, distinguished by the result's success field.
Call safeParse on a Zod schema with unknown input. It returns a discriminated result: a successful branch containing parsed data or a failure branch containing a ZodError, so callers can branch on success instead of wrapping parse in try/catch.
schema.safeParse(data: unknown): { success: true; data: T } | { success: false; error: ZodError }| Name | Type | Description |
|---|---|---|
data | unknown | The value to validate and parse; it is accepted as unknown input. |
A discriminated union: { success: true; data: T } on success, or { success: false; error: ZodError } on failure.
import { z } from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
const result = Player.safeParse({ username: 42, xp: "100" });
if (!result.success) {
console.error(result.error);
} else {
console.log(result.data);
}Checks the input without throwing, then uses the discriminant to access either the validation error or parsed data.
Validate request bodies, form submissions, or other untrusted values while keeping control flow explicit.
Return validation outcomes from a function without requiring callers to catch exceptions.
Inspect structured validation details and present useful feedback to users.
safeParse validates and returns a plain result object rather than throwing when validation fails. The result is a discriminated union with either success and data or failure and error.
Follow-up: What should you use for asynchronous refinements? Use safeParseAsync, because the synchronous method does not handle those asynchronous schema APIs.
Check result.success before reading result.data or result.error. A successful result contains the parsed value, while an unsuccessful result contains a ZodError with validation details.
Follow-up: Why is checking success useful in TypeScript? It narrows the discriminated union so each branch exposes only its valid property.
The input parameter is typed as unknown, so safeParse can accept untrusted data. The returned data is the schema's parsed type, while failures expose a ZodError.
Follow-up: How can asynchronous validation avoid exceptions? Await schema.safeParseAsync(input) and branch on its success field.
parsesafeParseAsyncZodError