Sub topic 9
Choosing when validation runs
This chapter covers the mode and reValidateMode options of useForm. It assumes you can already build a form with register, handleSubmit, and zodResolver, and that you read errors from formState.errors. You should also be comfortable with React hooks and basic TypeScript generics.
Why timing matters
A Zod schema describes what valid data looks like. It does not decide when the form checks the data. React Hook Form decides that, and you control it with the mode option.
The timing changes how the form feels:
- Errors that appear while someone is still typing their first character feel aggressive.
- Errors that appear only after pressing submit can feel late on a long form.
- Validating on every keystroke runs your schema more often, which costs work and renders.
There is no single best setting. You choose one based on the form and the people using it.
The validation modes
mode sets when validation runs before the first submit. The default is onSubmit.
| Mode | Validation runs | Typical use |
|---|---|---|
| `onSubmit` | When the form is submitted | Short forms, the default |
| `onBlur` | When a field loses focus | Longer forms with feedback per field |
| `onChange` | On every change event | Live feedback such as password rules |
| `onTouched` | On first blur, then on every change | Calm first pass, fast fixes afterward |
| `all` | On both blur and change | Rarely needed, highest cost |
Here is a form that validates when the user leaves a field.
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"),
password: z.string().min(8, "Use at least 8 characters"),
});<typeof schema>;
export function BlurForm() {
const {
register,
handleSubmit,
formState: { errors },
}({
resolver: zodResolver(schema),
defaultValues: { email: "", password: "" },
mode: "onBlur",
});
return (
<leSubmit((values) => console.log(values))} noValidate>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...register("email")} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<label htmlFor="password">Password</label>
<input id="password" type="password" {...register("password")password && <p role="alert">{errors.password.message}</p>}
<button type="submit">Create account</button>
</form>
);
}Tab typing anything and the "Email is required" message appears. With the default onSubmit mode, nothing would show until the user pressed the button.
Re-validation after a submit
After the first submit attempt, mode no longer controls timing. The reValidateMode option takes over. It accepts onChange (the default), onBlur, or onSubmit.
This explains a common pattern. With the defaults, a user submits, sees an error, fixes the field, and the error clears as they type. Validation was onSubmit before the first submit and became onChange afterward.
useForm<Values>({
resolver: zodResolver(schema),
mode: "onSubmit",
reValidateMode: "onChange",
});Setting reValidateMode: "onSubmit" makes errors stay on screen until the next submit. Most users find that frustrating, so use it only with a specific reason.
What the resolver validates on each event
With zodResolver, the resolver receives the whole form's values on each validation run. React Hook Form then reads the errors for the field that triggered the event and updates only that field's error state.
Two consequences follow:
- The whole schema runs even when one field changes. Keep expensive checks, such as a large
refine, in mind when you chooseonChange. - A field can show an error only after it has been validated. A field the user has not touched has no error in
onBluroronTouchedmode, even though its value is invalid.
Cross-field rules and timing
A refine on the whole object, like the password confirmation rule, only reports an error after the object's own fields pass. Zod skips the object-level refinement while any field in the object has failed. A user may type a mismatched confirmation and see no "Passwords do not match" message because another field is still invalid. The message appears once the other fields are valid.
Triggering validation manually
Sometimes the automatic timing is not enough. The trigger function from useForm runs validation on demand. Call it with a field name, an array of names, or nothing to validate every field.
This is useful in a multi-step form, where you validate the current step before moving on.
const { trigger } = useForm<Values>({
resolver: zodResolver(schema),
});
async function goToNextStep() {
const stepIsValid = await trigger(["email"]);
if (stepIsValid) {
// move to the next step
}
}trigger returns a promise that resolves to true when the checked fields are valid. It also puts any errors into formState.errors, so the messages render as usual.
If the dependent field needs checking when another field changes, use the deps option of register.
<input
{...register("password", { deps: ["confirmPassword"] })}
type="password"
/>When password is validated, confirmPassword is validated too. This keeps a mismatch message current when the user edits the first field after filling the second.
Reading validation state
formState exposes values that depend on the mode.
isValidreports whether the whole form currently passes the schema. It is reliable inonChange,onBlur,onTouched, andallmodes. InonSubmitmode it is not kept up to date in the same way, so do not rely on it to enable a button before the first submit.isValidatingis true while validation is running.touchedFieldsrecords which fields have lost focus.isSubmittedandsubmitCounttell you whether re-validation rules apply.
These values are read through a proxy. React Hook Form only tracks the parts of formState you read during render, so subscribing to isValid adds a subscription and some extra renders.
Choosing a mode
Use these questions to decide:
- Is the form short, with two or three fields? Use
onSubmit. Errors appear together, and the code is simplest. - Is it long, or does each field have strict rules? Use
onTouched. The user gets one calm check after leaving a field and fast feedback while fixing it. - Does the user need live guidance, such as a password strength rule? Use
onChangefor that form, or watch just that one field. - Do you want a disabled submit button until the form is valid? Use a mode other than
onSubmitand readisValid. Keep in mind that disabled buttons hide the reason for the problem from keyboard and screen reader users.
Common mistakes
- Expecting
modeto apply after submit. After the first submit,reValidateModeis in charge. - Using
isValidinonSubmitmode to enable the button. It may stayfalseor stale. Switch the mode or drop the disabled state. - Forgetting
defaultValues. An undefined starting value can make the first validation report a type error, such as "Required" or "Expected string", instead of your custom message. Provide empty strings. - Expecting a cross-field
refineto appear immediately. It waits for the object's fields to pass. - Calling
triggerwithoutawait. It returns a promise, so check its result only after it resolves.
Exercise
A form uses mode: "onBlur" and the default reValidateMode. A user tabs through the password field leaving it empty and sees an error. They submit, then start typing a valid password. When does the error clear, and which option controls that?
Show answer
It clears as the user types, on the change event. Because the form has been submitted, reValidateMode controls timing, and its default is onChange. The mode option only applied before the first submit.
Exercise
You have a password field and a confirmPassword field, and the mismatch rule uses refine on the object. Users edit password after filling in confirmPassword, and the old "Passwords do not match" error stays visible. What option on register("password") fixes this?
Show answer
Use deps: ["confirmPassword"], as in register("password", { deps: ["confirmPassword"] }). When password is validated, confirmPassword is validated as well, so its error updates.