React Tutorials

How to Add Confirm Password Validation in React with Hook Form

Confirming a password or matching a password is an important validation; it protects your users from creating a forgettable password.

When a user types password in the password input field, there are chances he might make a mistake in typing a password.

Because of this, he ended up creating a wrong password; however, it has a solution. In this tutorial, we are going to learn how to create confirm password validation in React app.

We start this guide with the basic setup of a fresh React app, install and configure some of the modules (React hook form and Yup JavaScript schema builder).

We will describe in detail how to use hook form and yup packages to add match password validation in React app from the absolute beginning.

React Hook Form Password Match and Confirm Password Validation Example

  • Step 1: Setting Up New App
  • Step 2: Install Yup and Hook Form Packages
  • Step 2: Install Bootstrap Library
  • Step 3: Implement Hook Form Confirm Password Validation
  • Step 4: Register App Js
  • Step 5: Run Development Server

Setting Up New App

Setting up new React app is easy, almost all of you know how it is done.

You can use create-react-app tool to generate a new react project.

npx create-react-app react-world

Once the app is installed, immediately enter into the root of the applicaiton.

cd react-world

Install Yup and Hook Form Packages

Creating and integrating validation in React is made easy by yup and hook form libraries. In this same step, we are going to install both libraries.

Without further ado, you need to execute the given command from the console.

npm install @hookform/resolvers yup

Install Bootstrap Library

Building a form in React requires HTML and CSS knowledge. If your hand is tight in CSS, don’t worry; we have a quick solution for you.

Yes, you can use the Bootstrap framework; this will allow you to create the form component in very little time.

npm install bootstrap

After installing the library created in the node_modules folder. So next, open the App.js file, inside here you need to add the bootstrap’s CSS path.

import 'bootstrap/dist/css/bootstrap.min.css'

Implement Hook Form Confirm Password Validation

We are going to build a ConfirmPassword.js file, this needs to be formed inside the components/ directory.

In this file you have to write the code that will help you implement the password match validation in React app.

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

export default function ConfirmPassword() {
  const formSchema = Yup.object().shape({
    password: Yup.string()
      .required('Password is mendatory')
      .min(3, 'Password must be at 3 char long'),
    confirmPwd: Yup.string()
      .required('Password is mendatory')
      .oneOf([Yup.ref('password')], 'Passwords does not match'),
  })

  const formOptions = { resolver: yupResolver(formSchema) }

  const { register, handleSubmit, reset, formState } = useForm(formOptions)

  const { errors } = formState

  function onSubmit(data) {
    console.log(JSON.stringify(data, null, 4))
    return false
  }

  return (
    <div className="container mt-5">
      <h2>React Confirm Password Validation Example</h2>

      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="form-group">
          <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">
          <label>Confirm Password</label>
          <input
            name="confirmPwd"
            type="password"
            {...register('confirmPwd')}
            className={`form-control ${errors.confirmPwd ? 'is-invalid' : ''}`}
          />
          <div className="invalid-feedback">{errors.confirmPwd?.message}</div>
        </div>

        <div className="mt-3">
          <button type="submit" className="btn btn-primary">
            Submit
          </button>
        </div>
      </form>
    </div>
  )
}

Register App Js

The following task is about adding the hook form component, you require to open the App.js file.

Register the ConfirmPassword component by importing into it.

import React from 'react'
import ConfirmPassword from './components/ConfirmPassword'
import 'bootstrap/dist/css/bootstrap.min.css';


export default function App() {
  return (
    <div className="App">
      <ConfirmPassword />
    </div>
  )
}

Run Development Server

All the major work has been done, so what testing is left and we are going to do it right now.

Make sure to type the following command on your terminal, there after run it to invoke the development server.

npm start

To see the app in utter action, use the provided url through your favourite browser.

http://localhost:3000

Conclusion

It is obvious some times you want your users to be more vigilant while creating a new password. At the time of creating a new password, they might type some wrong word that they might forget.

This is where confirm password field comes into play; in this post, we explained how to implement validation in the password component.

We figured out how to apply password match validation in React app. The hook form and yop plugins helped us for implementing match password validation in React.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

1 day ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

1 week ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago