React Hook Form ( + Yup + schema-to-yup )で バリデーションの設定をjsonで書いてフォームを作成する

● Yup + schema-to-yup のインストール

yarn add @hookform/resolvers yup
yarn add schema-to-yup

● 設定の記述例

import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';

MyLogin.tsx

  const validationSchema = {
    $schema: "http://json-schema.org/draft-07/schema#",
    $id: "http://example.com/person.schema.json",
    type: "object",
    properties: {
      email: {
        type: "string",
        format: "email",
        required: true,
      },
      password: {
        type: "string",
        required: true,
      },
    }
  };

  const validationConfig = {
    errMessages: {
      email: {
        required: "メールアドレスを入力してください",
        format: "メールアドレスの形式が正しくありません",
      },
      password: {
        required: "パスワードを入力してください",
      },
    },
  };
  const { buildYup } = require("schema-to-yup");
  const yupSchema = buildYup(validationSchema, validationConfig);

  const formOptions = { resolver: yupResolver(yupSchema) };
  const { register, handleSubmit, setValue, formState: { errors } } = useForm(formOptions);
  const onSubmit = async (data: any) => {
    alert('form送信されました');
  }

jsxはとてもシンプルに記述できます

return (
<form onSubmit={handleSubmit(onSubmit)}>
    <input id="email" type="email" {...register('email')} />
    <div>{errors.email?.message}</div>

    <input id="password" type="text" {...register('password')} />
    <div>{errors.password?.message}</div>
</form>
)
No.2144
01/20 17:40

edit