LoginSignup
1
0

React Hook Form でバリデーションを手動で trigger する方法

Last updated at Posted at 2023-08-12

以前調べたのでたまにはまとめようかなと

trigger は、React Hook Form でのフォームのバリデーションを手動でトリガーする関数です。依存するバリデーション(一つの入力のバリデーションが別の入力の値に依存する場合など)にも役立ちます。

引数として取るプロパティ

name

undefined
すべてのフィールドのバリデーションをトリガーします。
例: trigger()

string
特定のフィールドのバリデーションをトリガーします。
例: trigger("yourDetails.firstName")

string[]
複数のフィールドのバリデーションをトリガーします。
例: trigger(["yourDetails.lastName"])

shouldFocus
エラー設定時に入力にフォーカスするかどうか。入力の参照が登録されている場合のみ機能し、カスタム登録では機能しない。
例: trigger('name', { shouldFocus: true })

注意点
単一のフィールド名を文字列として
ターゲットにする場合のみレンダリングの最適化が適用されます。配列やundefinedをトリガーに提供した場合、全体のformStateが再レンダリングされます。

コード実装のポイント

  1. フォームの各入力に対するバリデーションルールの設定
  2. エラーメッセージの表示
  3. 全フィールドまたは特定のフィールドのバリデーションを手動でトリガーするボタンの実装
  4. エラーをクリアするボタンの実装
  5. フォームの送信時に入力データをアラートで表示
example.tsx
import * as React from "react";
import * as ReactDOM from "react-dom";
import { useForm } from "react-hook-form";
import "./styles.css";

// フォームの入力の型を定義
type FormInputs = {
  firstName: string;
  lastName: string;
  username: string;
};

function App() {
  // useFormから必要な関数やオブジェクトを取得
  const {
    register, // inputにバリデーションルールを登録するための関数
    formState: { errors }, // バリデーションエラー情報を持つオブジェクト
    trigger,  // 手動でバリデーションをトリガーする関数
    handleSubmit, // フォームの送信処理をハンドルする関数
    clearErrors  // エラー情報をクリアする関数
  } = useForm<FormInputs>({
    mode: "onChange"  // 入力時にリアルタイムでバリデーションを実行
  });

  // フォーム送信時の処理
  const onSubmit = (data: FormInputs) => {
    alert(JSON.stringify(data));
  };

  return (
    // handleSubmitを使用して、フォーム送信時の処理をハンドル
    <form onSubmit={handleSubmit(onSubmit)}>
      // 以下、各入力フィールドとエラーメッセージを表示
      <label>First name: </label>
      <input {...register("firstName", { required: true })} />
      {errors.firstName && <p>This field is Required</p>}

      <label>Last name: </label>
      <input {...register("lastName", { required: true })} />
      {errors.lastName && <p>This field is Required</p>}

      <label>Username: </label>
      <input {...register("username", { required: true })} />
      {errors.username && <p>This field is Required</p>}

      // エラー情報をクリアするボタン
      <button type="button" onClick={() => { clearErrors(); }}>Clear Errors</button>

      <input type="submit" />

      // 以下、手動でバリデーションをトリガーするボタン群
      // 全てのフィールドのバリデーションをトリガー 
      <button type="button" onClick={() => { trigger(); }}>Validate All</button>

      // fistName フィールドのみバリデーションをトリガー
      <button type="button" onClick={() => { trigger("firstName"); }}>Validate First Name</button>

      // fistName, lastName フィールドのバリデーションをトリガー
      <button type="button" onClick={() => { trigger(["firstName", "lastName"]); }}>Validate First And Last Name</button>

      // fistName フィールドのみバリデーションをトリガー。trigger関数は Promise を返すので、await を使用してその結果を待ち、その後に結果を表示する
      <button type="button" onClick={async () => { console.log("firstName", await trigger("firstName")); }}>Trigger Async First Name Validation</button>
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0