0

I'm validating my form using Joi 17.6.0 and useForm. I've added two fields, 'Password' and 'Confirm Password'. I've added the required validation for both of them. However, the required validation for the second field ('Confirm password') does not work. It only shows the message '"confirmPassword" must be [ref:password]"' when the password field meets the validations.

I've created this demo code in React.

import React from 'react'
import { useForm } from "react-hook-form";
import { joiResolver } from "@hookform/resolvers/joi";
import Joi from "joi";

interface IFormInput {
    password: string;
    confirmPassword: string;
}

const schema = Joi.object({
    password: Joi.string().required(),
    confirmPassword: Joi.string().required().equal(Joi.ref('password')),
});

const Contact = () => {
    const { register, handleSubmit, formState: { errors } } = useForm<IFormInput>({
        resolver: joiResolver(schema)
    });
    const onSubmit = (data: IFormInput) => {

        console.log(data);
    };

    return (
        <form id='form1' onSubmit={handleSubmit(onSubmit)}>
            <div>
                <input {...register("password")} />
                <label>{errors?.password?.message}</label>
            </div>
            <div>
                <input {...register("confirmPassword")} />
                <label>{errors?.confirmPassword?.message}</label>
            </div>
            <div><button type="submit">Submit</button></div>
        </form>
    );
}

export default Contact

Currently, The required validation only works for the password field.

enter image description here

I need the required validation also works for the Confirm password field. Something like this.

Thanks in advance.

enter image description here

0 Answers0