Sub topic 8
Reading form state and showing field errors
This chapter assumes you can write React function components and hooks, and that you have a form working with useForm, register, handleSubmit, and zodResolver. Here you will read what the form knows about itself through formState, and turn validation failures into messages next to the right inputs.
Where errors come from
When the user submits, handleSubmit runs your resolver. zodResolver parses the form values with your Zod schema. Each Zod issue becomes an entry in formState.errors, keyed by the field's path. If errors is empty, your submit callback runs. Otherwise React Hook Form re-renders with the errors and focuses the first invalid field.
The shape of formState
useForm returns a formState object. These are the properties you will use most.
| Property | Meaning |
|---|---|
| `errors` | Current validation errors, keyed by field name |
| `isSubmitting` | `true` while the async submit callback is running |
| `isSubmitted` | `true` after the first submit attempt |
| `isSubmitSuccessful` | `true` if the last submit finished without errors or a thrown exception |
| `submitCount` | Number of submit attempts |
| `isDirty` | `true` if any value differs from `defaultValues` |
| `dirtyFields` | Which fields differ from their defaults |
| `touchedFields` | Which fields the user has focused and left |
| `isValid` | `true` if the current values pass validation |
Each entry in errors is an object with a message and a type. With zodResolver, message is the string you gave Zod, and type is the Zod issue code, such as too_small. The entry also has a ref pointing at the input element, which you rarely need.
// errors after submitting an empty sign-up form
{
email: { type: "too_small", message: "Email is required", ref: /* input */ },
password: { type: "too_small", message: "Use at least 8 characters", ref: /* input */ }
}formState is subscription based
formState is a Proxy. React Hook Form re-renders your component for a state change only if you read that property during render. If you never read isDirty, a change to it costs nothing.
This has a practical consequence. Read the properties you need in the same render pass, preferably by destructuring from formState in the useForm call. Reading formState.isDirty only inside an event handler or a conditional branch can leave the subscription unregistered. The value then stays stale.
A complete form with field-level errors
This form shows one message per field, disables the button while submitting, and shows an "unsaved changes" hint using isDirty.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const profileSchema = z.object({
name: z.string().min(1, "Name is required"),
email: z.string().min(1, "Email is required").email("Enter a valid email"),
});
type ProfileValues = z.infer<typeof profileSchema>;
export function ProfileForm() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting, isDirty },
} = useForm<ProfileValues>({
resolver: zodResolver(profileSchema),
defaultValues: { name: "", email: "" },
});
const onSubmit = async (values: ProfileValues) => {
await new Promise((resolve) => setTimeout(resolve, 500));
console.log("saved", values);
};
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<label htmlFor="name">Name</label>
<input id="name" {...register("name")} />
{errors.name && <p role="alert">{errors.name.message}</p>}
<label htmlFor="email">Email</label>
<input id="email" type="email" {...register("email")} />
{errors.email && <p role="alert">{errors.email.message}</p>}
{isDirty && <p>You have unsaved changes.</p>}
<button type="submit" disabled={isSubmitting}>
Save
</button>
</form>
);
}noValidate on the form turns off the browser's built-in validation bubbles. Without it, type="email" can block the submit event before Zod runs, and your messages never appear.
Why a "required" message needs min(1)
Text inputs always produce strings. An empty input gives "", not undefined, so z.string() accepts it. Add .min(1, "Name is required") to make an empty field fail. This is why the schemas in this tutorial put min(1) before .email(). An empty email then shows "Email is required" rather than "Enter a valid email".
One message per field by default
A field can fail several rules at once. By default React Hook Form keeps only the first issue for each field (criteriaMode: "firstError"). Zod reports issues in schema order, so the order of your checks controls which message the user sees. Put the most basic rule first.
Nested and array errors
errors mirrors the shape of your values. Nested objects and arrays produce nested error objects, so you reach them with optional chaining:
{errors.address?.city && <p role="alert">{errors.address.city.message}</p>}
{errors.items?.[index]?.name && (
<p role="alert">{errors.items[index]?.name?.message}</p>
)}An array-level rule such as .min(1, "Add at least one item") reports on errors.items?.root?.message, and in some versions on errors.items?.message. Check what your installed version produces by logging errors once, then write the access path to match.
Errors that belong to no field
Some failures apply to the form as a whole, for example "Invalid credentials". Use the reserved root key. It is cleared on the next submit, unlike field errors set manually, which may persist until the field is revalidated.
setError("root.serverError", { type: "server", message: "Invalid credentials" });
// in JSX
{errors.root?.serverError && <p role="alert">{errors.root.serverError.message}</p>}Common mistakes
- Reading
isValidand seeingfalseon first render.isValidreflects validation of the current values. With the defaultonSubmitmode, it may not update until validation has run. If you need a live "can submit" state, setmode: "onChange"or"onBlur", which the next chapter covers. - Comparing
errorsto{}. UseObject.keys(errors).length === 0, or just rely onhandleSubmit. - Showing errors with
touchedFieldsonly. After a failed submit, untouched fields still carry errors. Show an error whenevererrors.fieldexists. - Checking
errors.email.typeagainst hand-written strings. Zod issue codes differ between Zod versions. Prefer showingmessage, and set the message in the schema. - Using
isSubmitSuccessfulto reset the form. Reset in an effect that depends on it, or callreset()at the end of your submit callback. Either way, do not callresetduring render.
Exercise
A form uses mode: "onSubmit" and formState: { errors }. A component below the form reads formState.isDirty inside a useEffect callback only, never during render, and its value is always false. Why, and what is the fix?
Show answer
formState is a Proxy that subscribes only to properties read during render. Reading isDirty only inside an effect never registers the subscription, so the value is not kept current. Fix it by reading isDirty during render, for example by adding it to the destructuring in formState: { errors, isDirty }, and then using that variable inside the effect.
Exercise
Your schema is z.object({ email: z.string().email("Enter a valid email") }). A user submits without touching the email input, but no "Enter a valid email" message appears next to the field. The input shows type="email" and the form has no noValidate. What is the likely cause?
Show answer
The browser's native validation is blocking the submit event for the type="email" input. The empty value passes native checks but other invalid values trigger the browser's bubble before handleSubmit runs. Add noValidate to the <form> so Zod performs the validation. Also add .min(1, "Email is required") so an empty string fails with a clear message.