大変便利なreact-hook-form。 便利なreact-hook-formにはdefaultで使えるvalidation機能があります。
<input {...register('firstName', { required: true, max: { value: 10, message: 'error' } })} />
このような形でregisterで登録するときに、optionsを指定すれば、ある程度のvalidationを実装することは可能です。 ただ、複数の入力項目になった場合、componentの内部で設定を持つと見にくいですし、設定の仕方も少し直感的ではないです。 そこで、react-hook-formではschema baseのvalidationを使用して、改善することができます。 今回はyupというmoduleを入れて、実装していきます。
導入
下記のmoduleを導入してください。
npm install @hookform/resolvers yup
サンプル
import { NextPage } from 'next'; import { useForm } from 'react-hook-form'; import React from 'react'; import * as yup from 'yup'; import { yupResolver } from '@hookform/resolvers/yup'; // validaton schemaの定義 const schema = yup.object({ firstName: yup.string().required(), age: yup.number().positive().integer().required(), }); // useFormで使用する型を定義 type InputType = yup.InferType<typeof schema>; const Validation: NextPage = () => { const { register, handleSubmit, formState: { errors }, } = useForm<InputType>({ resolver: yupResolver(schema), }); const onSubmit = (data: InputType): void => console.log(data); return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('firstName')} /> <p>{errors.firstName?.message}</p> <input {...register('age')} /> <p>{errors.age?.message}</p> <input type="submit" /> </form> ); }; export default Validation;
すごく簡単にvalidatonを拡張できますね! 事前にschemaを定義して、useFormでresolverを指定するだけで、validatonを行うことができます。 yupのほかにもZod,Superstruct,Joiといったライブラリに対応をしています。
お好きなライブラリを入れてみるといいかもですね!