How to validate password & confirm password in react-hook-form

Share

Initiate react-hook-form

const {register, handleSubmit, reset, formState: {errors}, watch} = useForm();

Set validation as like below

const confirm_password = useRef({});
confirm_password.current = watch('confirm_password', '');

 

Form field setup would be as

<Form.Group className='form-group'>
    <Form.Control
        type='password'
        placeholder='Enter Password'
        {...register('password',
            {
                required: 'Required',
            }
        )}
    />
    <p>{errors?.password?.message}</p>
</Form.Group>
<Form.Group className='form-group'>
    <Form.Control
        type='password'
        placeholder='Repeat Password'
        {...register('confirm_password',
            {
                validate: value =>
                    value === password.current || "The passwords do not match"
            }
        )}
    />
    <p>{error?.confirm_password?.message}</p>
</Form.Group>

 

If there are multiple forms on one page or comparison, see this POST to set up watch for multiple react-hook-form.


                                

Leave a Reply

Related Articles

No related articles