trigger: UseFormTrigger
Manually triggers form or input validation. This method is also useful when you have dependent validation (input validation depends on another input's value).
Props
| Name | Type | Description | Example |
|---|---|---|---|
| name | undefined | Triggers validation on all fields. | trigger() |
| string | Triggers validation on a specific field value by name | trigger("yourDetails.firstName") | |
| string[] | Triggers validation on multiple fields by name. | trigger(["yourDetails.lastName"]) | |
| shouldFocus | boolean | Since v7.7.0 Focuses the input when an error is set. This only works when the input's reference is registered, it will not work for custom register as well. | trigger('name', { shouldFocus: true }) |
RULES
Isolate render optimisation only applicable for targeting a single field name with string as payload, when supplied with array and undefined to trigger will re-render the entire formState.
Examples:
import { useForm } from "react-hook-form"type FormInputs = {firstName: stringlastName: string}export default function App() {const {register,trigger,formState: { errors },} = useForm<FormInputs>()return (<form><input {...register("firstName", { required: true })} /><input {...register("lastName", { required: true })} /><buttontype="button"onClick={() => {trigger("lastName")}}>Trigger</button><buttontype="button"onClick={() => {trigger(["firstName", "lastName"])}}>Trigger Multiple</button><buttontype="button"onClick={() => {trigger()}}>Trigger All</button></form>)}
Video
The following video explains trigger API in detail.
Thank you for your support
If you find React Hook Form to be useful in your project, please consider starring and supporting it.