Forms and feedback

Validate with React Hook Form and Zod

Connect a Zod schema to React Hook Form and infer one data shape without pretending client validation protects the server.

8 minute lesson

~~~

Our form accepts any project name right now, including an empty one. Let’s fix that with a Zod schema.

The schema is the list of rules for our form data. We can also use it to create the TypeScript type, so the rules and the type cannot drift apart.

import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { z } from 'zod'

const projectSchema = z.object({
  name: z.string().trim().min(3).max(60),
  description: z.string().trim().max(280).optional(),
})

type ProjectForm = z.infer<typeof projectSchema>

const form = useForm<ProjectForm>({
  resolver: zodResolver(projectSchema),
  defaultValues: { name: '', description: '' },
})

Now React Hook Form can validate the fields before calling our submit handler. It also knows the exact shape of the valid data.

Be careful though. This only improves the form experience in the browser. Run the same schema in the Server Action too, because anyone can send a request without using our form.

Normalization is part of the contract. Decide whether a blank description becomes undefined or an empty string, and make that decision before persistence. Complete default values keep controls from switching between uncontrolled and controlled state and make failed submissions easier to restore. Choose validation timing deliberately; validating every keystroke can be noisy.

Use safeParse again on the server and map expected issues to a small serializable error shape. Do not return the entire Zod result, database exception, or rejected payload to the browser. Authorization is a separate check and must run even when the schema succeeds.

Try empty, whitespace-only, valid, and overlong values. Then forge a direct request and verify that server validation agrees with the client while server authorization independently decides whether this user may create a project.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →