Skip to content
jshacks.dev
Frameworks

Validate a form with React Hook Form and Zod

Connect a Zod 4 schema to React Hook Form with zodResolver, so validation rules live in one schema and errors map to each field.

1 min read
Summarize in AI

Validation written inside the component is hard to reuse. A Zod schema holds the rules, and the resolver feeds its errors to the form.

src/SignupForm.jsxJSX
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  email: z.email('Enter a valid email'),
  age: z.coerce.number().min(18, 'Must be 18 or older'),
});

export function SignupForm() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({ resolver: zodResolver(schema) });

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <input {...register('email')} />
      <p>{errors.email?.message}</p>
      <input type="number" {...register('age')} />
      <p>{errors.age?.message}</p>
      <button>Sign up</button>
    </form>
  );
}
Text
(submit with "nope" and 16)   -> Enter a valid email / Must be 18 or older
(submit with [email protected] and 30)
{ email: '[email protected]', age: 30 }

register connects an input and handleSubmit calls your function only when the schema passes. z.coerce.number() converts the string from the input to a number first. The resolver comes from @hookform/resolvers, and a version that supports Zod 4 is needed, as the resolver docs note.

Reuse the same schema on the server and parse the request body there, since client validation is only a convenience.

Taggedzod 4
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.