0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Hook Formでバリデーションを実装

Posted at

インストール用コマンド

npm install react-hook-form

フォームの実装方法

// useFormをインポート
import { useForm } from "react-hook-form";

// useFormからregisterとhandleSubmitを呼び出す
const { register, handleSubmit } = useForm();

// onSubmitを定義(本来は引数dataの型はしっかり定義する)
const onSubmit = (data: any) => {
    console.log(data);
};
// フォーム全体にhandleSubmitを適用する
<Box component={"form"} onSubmit={handleSubmit(onSubmit)}>
    // 中身は省略
</Box>

バリデーションの実装方法

用意されているバリデーション

下記のようなフォームでよく使われるバリデーションは用意されている。

  • required: "必須入力"
  • max: "最大値"
  • min: "最小値"
  • maxLength: "最大文字数"
  • minLength: "最小文字数"
  • pattern: "正規表現(メールアドレスなど)"

<例>

<Controller 
    {...register('content', {
        required: '内容を入力してください。',
        maxLength: {
        value: 50,
        message: '内容は50文字以内で入力してください。'
        }
    })}
    control={control}
    render={({ field }) => (
        <TextField 
        {...field}
        error={!!errors.content}
        helperText={errors.content?.message as string}
        label="内容"
        type="text" />
    )}
/>

オリジナルで作成できるバリデーション

<Controller 
    {...register('amount', {
        validate: (data) => {
            if (data === 0) {
                return '金額を入力してください。'
            }
        }
    })}
    control={control}
    render={({ field }) => (
        <TextField
        {...field}
        value={field.value === 0 ? "" : field.value}
        onChange={(e) => {
            const newValue = parseInt(e.target.value) || 0
            field.onChange(newValue)
        }}
        error={!!errors.amount}
        helperText={errors.amount?.message as string}
        label="金額"
        type="number" />
    )}
/>

エラー処理

// useFormからerrorsオブジェクトを取り出す
const {
    register,
    formState: { errors }, // useFormに追加
    handleSubmit,
  } = useForm();

// 各フォームのinput要素(TextFieldにエラーを表示)
<TextField 
 error={!!errors.content}
 helperText={errors.content?.message as string}
/>

以上

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?