[React]react hook formバリデーションでパスワードの一致の確認

getValues('name')でnameに設定している値を取得できる

import { useForm } from 'react-hook-form'

const { register, handleSubmit, watch, errors, getValues } = useForm();
const onSubmit = data => console.log(data);

<p className={classes.plate}>パスワード</p>
               <TextField
                   type="password"
                   value={password}
                   onChange={inputPassword}
                   name="password"
                   inputRef={register({
                       required: "You must specify a password",
                       minLength: {
                           value: 8,
                           message: "Password must have at least 6 characters"
                       }
                   })}
               />
               {errors.password && <p>{errors.password.message}</p>}
               <p className={classes.plate}>パスワード(確認)</p>
               <TextField
                   type="password"
                   value={passwordConfirm}
                   onChange={inputPasswordConfirm}
                   name="passwordConfirm"
                   inputRef={register({
                       validate: value =>
                           value === getValues('password') || <span>パスワードが一致しません</span>,
                           required: 'Password required',
                           minLength: { value: 8, message: 'Too short' }
                   })}
               />
               {errors.passwordConfirm && <p>{errors.passwordConfirm.message}</p>}

いいなと思ったら応援しよう!