trigger
Manually trigger validation without submitting.
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). trigger returns Promise<boolean>, resolving true when the targeted field(s) pass validation and false otherwise.
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 }) |
| shouldTouch | boolean | Since v7.87.0 Marks the targeted field(s) as touched, regardless of the validation result. Useful for validating and touching a field (or the whole form) without reaching for setValue's shouldTouch option as a workaround. | trigger('name', { shouldTouch: true }) |
RULES
Render-optimization isolation only applies when you target a single field by passing a string name. Passing an array of names, or calling trigger() with no arguments, re-renders the entire form state.
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.