Sub topic 8
Reading form state and showing field errors
This chapter assumes you can build a form with useForm, register, and handleSubmit, and that you have connected a Zod schema with zodResolver. Here you will read what the form reports back and show it to the user.
What formState contains
useForm returns a formState object that describes the form's current condition. These are the properties you will use most:
| Property | Meaning |
|---|---|
| `errors` | Validation messages, keyed by field name |
| `isSubmitting` | `true` while an async `onSubmit` is running |
| `isDirty` | `true` once any value differs from `defaultValues` |
| `touchedFields` | Fields the user has focused and left |
| `isValid` | `true` when the current values pass the schema |
React Hook Form wraps formState in a proxy. It re-renders your component only for the properties you read during render. If you never read isDirty, changes to it cause no render.
How errors get there
The resolver converts each Zod issue into an entry in errors. The entry's message comes from the string you passed to the Zod rule, such as "Use at least 8 characters".
Showing a field error
Each entry in errors has a message and a type. The entry is undefined when the field is valid, so check it before you read message.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const schema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
});
type Values = z.infer<typeof schema>;
export function EmailForm() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting, isDirty },
} = useForm<Values>({
resolver: zodResolver(schema),
defaultValues: { email: "" },
});
return (
<form onSubmit={handleSubmit((values) => console.log(values))} noValidate>
<input type="email" {...register("email")} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<button type="submit" disabled={isSubmitting || !isDirty}>
Save
</button>
</form>
);
}Here isDirty keeps the button disabled until the user changes something.
Nested and array errors
Errors follow the shape of your data. For an object field address.city, read errors.address?.city?.message. For an array, read errors.items?.[index]?.name?.message. Use optional chaining at every level, because any parent can be missing.
An array-level rule, such as .min(1) on the array itself, reports on errors.items?.root?.message rather than errors.items?.message. This is a common surprise.
Common mistakes
- Reading
errors.email.messagewithout checkingerrors.emailfirst throws when the field is valid. - Using
isValidto gate a submit button can disable it on a fresh form before the user has typed anything. The defaultonSubmitvalidation mode does not compute it until a submit, soisValidcan lag. - Rendering
errors.emailitself as a child fails, because it is an object. Render itsmessage.
Exercise
A form has a schema field tags: z.array(z.string()).min(1, "Add a tag"). Which expression reads the "Add a tag" message, and why not errors.tags?.message?
Show answer
Use errors.tags?.root?.message. A rule on the array itself is stored under root, so errors.tags?.message is undefined. Per-item errors are stored by index, as in errors.tags?.[0]?.message.