Course contentsShow
← React
Lesson 1237 of 2,39631. Forms in ReactFree lesson

Schema Validation Methods: parse vs safeParse

Learning when to use parse (throws on error) versus safeParse (returns success/error object) for different validation contexts.

Schema Validation Methods: parse vs safeParse

You'll learn: How to choose between Zod's parse and safeParse methods based on whether you want errors thrown or returned as data.

Two Ways to Validate

When validating data with Zod schemas, you have two main methods:

parse() validates your data and throws an error if validation fails. It's like a strict bouncer who won't let invalid data pass — the whole operation stops immediately.

safeParse() validates your data and returns an object describing success or failure. It's like a diplomatic bouncer who gives you a report card instead of kicking you out.

When to Use parse()

Use parse() when you're confident the data should be valid, and an error is truly exceptional:

const userSchema = z.object({ name: z.string() });

// In server actions or API routes where failure is exceptional
try {
  const validUser = userSchema.parse(serverData);
  // Continue with validUser
} catch (error) {
  // Log critical error, return 500
}

When to Use safeParse()

Use safeParse() in forms and user-facing validation where errors are expected and need gentle handling:

const result = userSchema.safeParse(formData);

if (!result.success) {
  // Show friendly error messages to user
  setErrors(result.error.flatten());
  return;
}

// Continue with result.data

With React Hook Form's Zod resolver, safeParse() runs behind the scenes — errors become form validation messages, not thrown exceptions.

The Core Difference

Think of parse() as "fail fast" for programmer errors, and safeParse() as "fail gracefully" for user errors.

Key Takeaway: Use parse() when invalid data is a bug (throw and crash), and safeParse() when invalid data is expected user input (handle gracefully with error objects).