npm i react-hook-form
npm i @hookform/resolvers yup
npm i schema-to-yup
または
yarn add react-hook-form
yarn add @hookform/resolvers yup
yarn add schema-to-yup
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { buildYup } from "schema-to-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 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>
)