Published: September 15 2021

React Hook Form - Password and Confirm Password Match Validation Example

Example built with React 17.0.2 and React Hook Form 7.15.3

This is a quick example of how to validate that a password and confirm password field match in React using the React Hook Form library. For a more detailed registration form example that includes this a bunch of other fields see React Hook Form 7 - Form Validation Example.

Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/react-hook-form-confirm-password-match-validation)


React Hook Form App Component with Password Match Validation

The app component contains an example form built with the React Hook Form library that contains a password and a confirm password field, both fields are required, the password field must have a minimum of 6 characters, and the confirm password field must match the password field.

Form validation rules are defined with the Yup schema validation library and passed with the formOptions to the React Hook Form useForm() function, for more info on Yup see https://github.com/jquense/yup.

The password and confirm password match validation is set with the rule Yup.string().oneOf([Yup.ref('password')], 'Passwords must match'). The .oneOf() method accepts an array of whitelisted values for the field, the value in the array (Yup.ref('password')) returns a reference to the value of password field, the second parameter to .oneOf() is the validation message to display if the passwords don't match ('Passwords must match').

The useForm() hook function returns an object with methods for working with a form including registering inputs, handling form submit, resetting the form, accessing form state, displaying errors and more, for a complete list see https://react-hook-form.com/api/useform.

The onSubmit() method is called when the form is valid and submitted, and simply displays the form data in a javascript alert.

The returned JSX template contains the form with the password field, confirm password field and validation message. The form fields are registered with the React Hook Form by calling the register function with the field name from the input element (i.e. {...register('password')}).

import React from 'react';
import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

function App() {
    // form validation rules 
    const validationSchema = Yup.object().shape({
        password: Yup.string()
            .required('Password is required')
            .min(6, 'Password must be at least 6 characters'),
        confirmPassword: Yup.string()
            .required('Confirm Password is required')
            .oneOf([Yup.ref('password')], 'Passwords must match')
            
    });
    const formOptions = { resolver: yupResolver(validationSchema) };

    // get functions to build form with useForm() hook
    const { register, handleSubmit, reset, formState } = useForm(formOptions);
    const { errors } = formState;

    function onSubmit(data) {
        // display form data on success
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(data, null, 4));
        return false;
    }

    return (
        <div className="card m-3">
            <h5 className="card-header">React Hook Form - Password and Confirm Password Match Validation</h5>
            <div className="card-body">
                <form onSubmit={handleSubmit(onSubmit)}>
                    <div className="form-row">
                        <div className="form-group col">
                            <label>Password</label>
                            <input name="password" type="password" {...register('password')} className={`form-control ${errors.password ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.password?.message}</div>
                        </div>
                        <div className="form-group col">
                            <label>Confirm Password</label>
                            <input name="confirmPassword" type="password" {...register('confirmPassword')} className={`form-control ${errors.confirmPassword ? 'is-invalid' : ''}`} />
                            <div className="invalid-feedback">{errors.confirmPassword?.message}</div>
                        </div>
                    </div>
                    <div className="form-group">
                        <button type="submit" className="btn btn-primary mr-1">Register</button>
                        <button type="button" onClick={() => reset()} className="btn btn-secondary">Reset</button>
                    </div>
                </form>
            </div>
        </div>
    )
}

export { App };

 


Need Some React Hook Form Help?

Search fiverr for freelance React Hook Form developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by