React 18 Password Strength Checker or Strength Indicator Tutorial

Author: | Published: | Updated: | Category: React JS

A strong password stops hackers from easily guessing or penetrating your account. A strong password is a password that contains any permutation of symbols, characters and numbers.

In this tutorial, we will teach you how to build a simple password strength indicator in React js application using a functional component.

To create a password strength checker tool in React, we’ll create a form component with the password input field.

As the user starts creating a strong password, our React password strength meter will notify password strength signals through various colour schemes:

  • Weak password: Red
  • Good password: Yellow
  • Exemplary password: Blue
  • Powerful password: Green

A strong password has certain traits:

  • It must include one uppercase letter.
  • It must contain one lowercase letter.
  • It must have one number.
  • It must include one special symbol (: @$! % * ? &).

This tutorial will show you how to validate a strong password. Hence, we will validate a password strength through our React strength meter component.

Create New React App

Open the terminal, type the command then execute command to create a new React application.

Make sure to land into the project folder.

npx create-react-app react-demo
cd react-demo

Create Password Strength Meter

To build the strength checker tool make StrengthMeter.js file inside the components folder within the src folder.

import React from "react";
import "./StrengthMeter.css";
const StrengthMeter = (props) => {
  const pwdValidate = props.password;
  const initPwdChecker = () => {
    let pwdCheck = 0;
    let validateRegex = ["[A-Z]", "[a-z]", "[0-9]", "\\W"];
    validateRegex.forEach((regex, i) => {
      if (new RegExp(regex).test(pwdValidate)) {
        pwdCheck += 1;
      }
    });
    switch (pwdCheck) {
      case 0:
        return {
          strength: 0,
          val: "",
        };
      case 1:
        return {
          strength: 1,
          val: "weak",
        };
      case 2:
        return {
          strength: 2,
          val: "fair",
        };
      case 3:
        return {
          strength: 3,
          val: "good",
        };
      case 4:
        return {
          strength: 4,
          val: "strong",
        };
      default:
        return null;
    }
  };
  {
    props.actions(initPwdChecker().val);
  }
  return (
    <>
      <div className="wrapper">
        <progress
          className={`pwd-checker-bar strength-${initPwdChecker().val}`}
          value={initPwdChecker().strength}
          max="4"
        />
        <br />
        <p className="pwd-label">
          {props.password && (
            <div>
              <p className={`label strength-${initPwdChecker().val}`}>
                Password strength validation:
                <strong>{initPwdChecker().val} </strong>
              </p>
            </div>
          )}
        </p>
      </div>
    </>
  );
};
export default StrengthMeter;

Add CSS to Password Checker Component

Now, we will write custom CSS to style the password checker, hence make the the components/StrengthMeter.css file and ensure that you have added the given code inside the file.

.wrapper {
  width: 520px;
  text-align: left;
  margin: 55px auto;
}
.wrapper {
  margin: 0 auto;
}
.pwd-checker-bar {
  -webkit-appearance: none;
  appearance: none;
  width: 100%;
  height: 10px;
}
.pwd-checker-bar::-webkit-progress-bar {
  background-color: rgb(246, 241, 241);
  border-radius: 4px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  -ms-border-radius: 4px;
  -o-border-radius: 4px;
}
.pwd-label {
  font-size: 22px;
}
.pwd-checker-bar::-webkit-progress-value {
  border-radius: 4px;
  background-size: 30px 18px, 100% 100%, 100% 100%;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  -ms-border-radius: 4px;
  -o-border-radius: 4px;
}
.label {
  margin-top: 10px;
  margin-bottom: 0px;
}
.strength-weak::-webkit-progress-value {
  background-color: #e20b07;
}
.strength-fair::-webkit-progress-value {
  background-color: #ebbd04;
}
.strength-good::-webkit-progress-value {
  background-color: #0b75ed;
}
.strength-strong::-webkit-progress-value {
  background-color: #01a917;
}
.weak span {
  color: #e20b07;
}
.strength-fair span {
  color: #ebbd04;
}
.strength-good span {
  color: #0b75ed;
}
.strength-strong span {
  color: #01a917;
}

Integrate Password Strength Checker

Create the new file components/Form.js file with the given code.

This file will hold the form that contains the form, we have integrated the password strength checker to the password input.

import React, { useState } from "react";
import StrengthMeter from "./StrengthMeter";
const Form = () => {
  const [pwdInput, initValue] = useState({
    password: "",
  });
  const [isError, setError] = useState(null);
  const onChange = (e) => {
    let password = e.target.value;
    initValue({
      ...pwdInput,
      password: e.target.value,
    });
    setError(null);
    let caps, small, num, specialSymbol;
    if (password.length < 4) {
      setError(
        "Password should contain minimum 4 characters, with one UPPERCASE, lowercase, number and special character: @$! % * ? &"
      );
      return;
    } else {
      caps = (password.match(/[A-Z]/g) || []).length;
      small = (password.match(/[a-z]/g) || []).length;
      num = (password.match(/[0-9]/g) || []).length;
      specialSymbol = (password.match(/\W/g) || []).length;
      if (caps < 1) {
        setError("Must add one UPPERCASE letter");
        return;
      } else if (small < 1) {
        setError("Must add one lowercase letter");
        return;
      } else if (num < 1) {
        setError("Must add one number");
        return;
      } else if (specialSymbol < 1) {
        setError("Must add one special symbol: @$! % * ? &");
        return;
      }
    }
  };
  const [isStrong, initRobustPassword] = useState(null);
  const initPwdInput = async (childData) => {
    initRobustPassword(childData);
  };
  const onSubmit = async (e) => {
    try {
      e.preventDefault();
      e.persist();
    } catch (error) {
      throw error;
    }
  };
  return (
    <div className="center">
      <h2>React Password Strength Validation Component Example</h2>
      <form onSubmit={onSubmit}>
        <label>
          <strong>Password</strong>
        </label>
        {isError !== null && <p className="errors"> - {isError}</p>}
        <input
          type="password"
          id="password"
          name="password"
          onChange={onChange}
          required
        />
        <StrengthMeter password={pwdInput.password} actions={initPwdInput} />
        {isStrong === "strong" && <button type="submit"> Register </button>}
      </form>
    </div>
  );
};
export default Form;

Update Global React Component

In this last section, we will update the global React component thus add the following code into the App.js.

import Form from "./components/Form";
function App() {
  return (
    <div>
      <Form />
    </div>
  );
}
export default App;

Run Development Server

Let us start the React development server using the npm start command, and make sure to test the application on the browser.

npm start
http://localhost:3000

React Password Strength Checker or Strength Indicator Tutorial

Loved this? Share it with others:
Digamber - Author positronX.io

An experienced full-stack developer with a passion for providing top-notch web experiences, proficient in developing both the front and back ends of a web application by utilizing the expertise of HTML, CSS, JavaScript, PHP, and Python.