Sub topic 9
Choosing when validation runs
This chapter assumes you can build a form with useForm, register, and handleSubmit, and that zodResolver is already connected to a Zod schema. Here you decide when that schema runs.
The mode option
useForm takes a mode option. It controls when validation first runs for a field, before the user has submitted.
| Mode | Validation runs |
|---|---|
| `onSubmit` (default) | When the user submits |
| `onBlur` | When a field loses focus |
| `onChange` | On every change event |
| `onTouched` | On the first blur, then on every change |
| `all` | On both blur and change |
A second option, reValidateMode, applies after the first submit. Its default is onChange, so a field with an error clears as soon as the user fixes it.
Setting a mode
This sign-up form validates a field after the user leaves it, then re-checks it on each keystroke.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const signUpSchema = 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"),
});
type SignUpValues = z.infer<typeof signUpSchema>;
export function SignUpForm() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
defaultValues: { email: "", password: "" },
mode: "onTouched",
reValidateMode: "onChange",
});
return (
<form onSubmit={handleSubmit((values) => console.log(values))} noValidate>
<input type="email" {...register("email")} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<input type="password" {...register("password")} />
{errors.password && <p role="alert">{errors.password.message}</p>}
<button type="submit">Create account</button>
</form>
);
}With onTouched, a user who is still typing their first email address does not see "Enter a valid email" after the first character. The error appears after they tab away. Once it appears, it updates on each keystroke.
How the resolver fits in
The resolver validates the whole form each time. React Hook Form then reports only the errors for the field being checked, so a blur on email does not show a password error.
Trade-offs
onSubmitgives the least noise and the fewest schema runs. Users find out about every problem at once.onChangegives instant feedback. It also shows errors on half-typed values and runs the schema on every keystroke.onTouchedis a good default for text fields. It waits for the first blur, then gives live feedback.formState.isValidis useful for disabling a submit button. Reading it makes the form compute validity from the schema as values change, so use it deliberately.
Validating on demand
Call trigger to validate without waiting for an event. trigger("email") checks one field, and trigger() checks all of them. A multi-step form can use it to check the current step before moving on.
Exercise
A form uses mode "onSubmit" and the default reValidateMode. A user submits with an invalid email, then corrects it. When does the error disappear, and why?
Show answer
It disappears as soon as the user changes the field, without another submit. After the first submit attempt, reValidateMode takes over, and its default is "onChange".