Skip to content

trigger

Trigger validation across the form

trigger: (name?: string | string[]) => Promise<boolean>

Manually triggers form or input validation. This method is also useful when you have dependant validation (input validation depends on another input's value).

Props

NameTypeDescriptionExample
nameundefinedTriggers validation on all fields.trigger()
stringTriggers validation on a specific field value by nametrigger("yourDetails.firstName")
string[]Triggers validation on multiple fields by name.trigger(["yourDetails.lastName"])
shouldFocusboolean

Should focus the input during setting an error. This only works when the input's reference is registered, it will not work for custom register as well.

trigger('name', { shouldFocus: true })
import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, trigger, formState: { errors } } = useForm();

  return (
    <form>
      <input {...register("firstName", { required: true })} />
      <input {...register("lastName", { required: true })} />
      <button
        type="button"
        onClick={async () => {
          const result = await trigger("lastName");
          // const result = await trigger("lastName", { shouldFocus: true }); allowed to focus input
        }}
      >
        Trigger
      </button>
      <button
        type="button"
        onClick={async () => {
          const result = await trigger(["firstName", "lastName"]);
        }}
      >
        Trigger Multiple
      </button>
      <button
        type="button"
        onClick={() => {
          trigger();
        }}
      >
        Trigger All
      </button>
    </form>
  );
}
import React from "react";
import { useForm } from "react-hook-form";

type FormInputs = {
  firstName: string
  lastName: string
}

export default function App() {
  const { register, trigger, formState: { errors } } = useForm<FormInputs>();

  return (
    <form>
      <input {...register("firstName", { required: true })} />
      <input {...register("lastName", { required: true })} />
      <button type="button" onClick={() => { trigger("lastName"); }}>Trigger</button>
      <button type="button" onClick={() => { trigger(["firstName", "lastName"]); }}>Trigger Multiple</button>
      <button type="button" onClick={() => { trigger(); }}>Trigger All</button>
    </form>
  );
}

Video

The following video explain trigger API in detail.

We Need Your Support

If you find React Hook Form to be useful in your React project, please star to support the repo and contributors ❤

Edit