Clue Mediator

Password and Confirm Password validation in React

📅January 28, 2022

Today we will show you an example of the password and confirm password validation in React. Sometimes we need to add the password and confirm password field in react form so I will show you the step-by-step how to validate password and confirm password using React Hooks.

Checkout more articles on ReactJS

Demo Application

Output - Password and Confirm Password validation in React - Clue Mediator

Output - Password and Confirm Password validation in React - Clue Mediator

Steps to add a password and confirm password validation in React

  1. Create a react application
  2. Design a form
  3. Add validation
  4. Output

1. Create a react application

We need to create a simple react application using create-react-app. We don’t need to install any NPM package to handle the validation. Run the following command to create a react app.

npx create-react-app pwd-validation-react

2. Design a form

Let’s create a form that contains Username, Password, and Confirm Password.

App.js

import React, { useState } from 'react';

function App() {

  const [input, setInput] = useState({
    username: '',
    password: '',
    confirmPassword: ''
  });

  const [error, setError] = useState({
    username: '',
    password: '',
    confirmPassword: ''
  })

  const onInputChange = e => {

  }

  const validateInput = e => {

  }

  return (
    <div class="app">
      <h4>Password and Confirm Password validation in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
      <form>

        <input type="text" name="username" placeholder="Enter Username" value={input.username} onchange={onInputChange} onblur={validateInput}>
        {error.username && <span class="err">{error.username}</span>}

        <input type="password" name="password" placeholder="Enter Password" value={input.password} onchange={onInputChange} onblur={validateInput}>
        {error.password && <span class="err">{error.password}</span>}

        <input type="password" name="confirmPassword" placeholder="Enter Confirm Password" value={input.confirmPassword} onchange={onInputChange} onblur={validateInput}>
        {error.confirmPassword && <span class="err">{error.confirmPassword}</span>}

        <button>Submit</button>
      </form>
    </div>
  );
}

export default App;

3. Add validation

Now let’s add the validation `onBlur` and `onChange` events where we will check the required validation and password match validation.

const onInputChange = e => {
  const { name, value } = e.target;
  setInput(prev => ({
    ...prev,
    [name]: value
  }));
  validateInput(e);
}

const validateInput = e => {
  let { name, value } = e.target;
  setError(prev => {
    const stateObj = { ...prev, [name]: "" };

    switch (name) {
      case "username":
        if (!value) {
          stateObj[name] = "Please enter Username.";
        }
        break;

      case "password":
        if (!value) {
          stateObj[name] = "Please enter Password.";
        } else if (input.confirmPassword && value !== input.confirmPassword) {
          stateObj["confirmPassword"] = "Password and Confirm Password does not match.";
        } else {
          stateObj["confirmPassword"] = input.confirmPassword ? "" : error.confirmPassword;
        }
        break;

      case "confirmPassword":
        if (!value) {
          stateObj[name] = "Please enter Confirm Password.";
        } else if (input.password && value !== input.password) {
          stateObj[name] = "Password and Confirm Password does not match.";
        }
        break;

      default:
        break;
    }

    return stateObj;
  });
}

4. Output

Let’s combine all code together and see how it looks.

App.js

import React, { useState } from 'react';

function App() {

  const [input, setInput] = useState({
    username: '',
    password: '',
    confirmPassword: ''
  });

  const [error, setError] = useState({
    username: '',
    password: '',
    confirmPassword: ''
  })

  const onInputChange = e => {
    const { name, value } = e.target;
    setInput(prev => ({
      ...prev,
      [name]: value
    }));
    validateInput(e);
  }

  const validateInput = e => {
    let { name, value } = e.target;
    setError(prev => {
      const stateObj = { ...prev, [name]: "" };

      switch (name) {
        case "username":
          if (!value) {
            stateObj[name] = "Please enter Username.";
          }
          break;

        case "password":
          if (!value) {
            stateObj[name] = "Please enter Password.";
          } else if (input.confirmPassword && value !== input.confirmPassword) {
            stateObj["confirmPassword"] = "Password and Confirm Password does not match.";
          } else {
            stateObj["confirmPassword"] = input.confirmPassword ? "" : error.confirmPassword;
          }
          break;

        case "confirmPassword":
          if (!value) {
            stateObj[name] = "Please enter Confirm Password.";
          } else if (input.password && value !== input.password) {
            stateObj[name] = "Password and Confirm Password does not match.";
          }
          break;

        default:
          break;
      }

      return stateObj;
    });
  }

  return (
    <div class="app">
      <h4>Password and Confirm Password validation in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
      <form>

        <input type="text" name="username" placeholder="Enter Username" value={input.username} onchange={onInputChange} onblur={validateInput}>
        {error.username && <span class="err">{error.username}</span>}

        <input type="password" name="password" placeholder="Enter Password" value={input.password} onchange={onInputChange} onblur={validateInput}>
        {error.password && <span class="err">{error.password}</span>}

        <input type="password" name="confirmPassword" placeholder="Enter Confirm Password" value={input.confirmPassword} onchange={onInputChange} onblur={validateInput}>
        {error.confirmPassword && <span class="err">{error.confirmPassword}</span>}

        <button>Submit</button>
      </form>
    </div>
  );
}

export default App;

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project