How to Create Password Strength Checker in React Js

This guide will teach you how to create a Password strength checker in React application. We’ll build an input field that shows various signals for password strength.

To create a password strength checker in React, we will not take the help of any third-party library. You will be using custom code to validate whether the password is strong or not in React.

Password strength is a security measure that identifies the effectiveness of a password against guessing or brute-force attacks.
Password strength offers the first line of defence against unwanted access to your system.

To create a stronger password in React, your password must contain one uppercase letter, one lowercase letter, one number, and one special Character (: @$! % * ? &).

We will highlight password strength through colour indicators:

  • Strong password: Green colour
  • Weak password: Red colour
  • Adequate password: Yellow colour
  • Exemplary password: Blue colour

React Password Strength Meter Example

  • Step 1: Install React Project
  • Step 2: Build Password Strength Checker
  • Step 3: Style Password Meter Component
  • Step 4: Implement Strength Checker to Input
  • Step 5: Update App Component
  • Step 6: View App on Browser

Install React Project

Move to console, run the following command then press enter to install the React app.

npx create-react-app react-password-meter

Build Password Strength Checker

Move to src/ folder, create features/ folder, then create PasswordStrengthChecker.js file then insert the given code in the file.

import React from "react";
import "./PwdMeter.css";

const PasswordStrengthChecker = (props) => {
  const validatedOutput = props.password;
  const setPwdMeter = () => {
    let strengthVal = 0;
    let checkRegex = ["[A-Z]", "[a-z]", "[0-9]", "\\W"];
    checkRegex.forEach((regex, i) => {
      if (new RegExp(regex).test(validatedOutput)) {
        strengthVal += 1;
      }
    });
    switch (strengthVal) {
      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(setPwdMeter().val);
  }

  return (
    <>
      <div className="container">
        <progress
          className={`strength-meter-bar pwdStength-${setPwdMeter().val}`}
          value={setPwdMeter().strength}
          max="4"
        />
        <br />
        <p className="password-checker-label">
          {props.password && (
            <>
              <div>
                <p className={`label pwdStength-${setPwdMeter().val}`}>
                  Password checker: <strong>{setPwdMeter().val} </strong>
                </p>
              </div>
            </>
          )}
        </p>
      </div>
    </>
  );
};

export default PasswordStrengthChecker;

Style Password Meter Component

Then in the features folder, create the PwdMeter.css file; In this file, we will add the styling code for designing the password strength meter component.

.center,
.container {
  text-align: left;
  width: 500px;
  margin: 50px auto;
}

.container {
  margin: 0 auto;
}

.strength-meter-bar {
  -webkit-appearance: none;
  appearance: none;
  width: 100%;
  height: 8px;
}
.strength-meter-bar::-webkit-progress-bar {
  background-color: rgb(243, 239, 239);
  border-radius: 4px;
}
.password-checker-label {
  font-size: 18px;
}
.strength-meter-bar::-webkit-progress-value {
  border-radius: 3px;
  background-size: 30px 18px, 100% 100%, 100% 100%;
}
.label {
  margin-top: 10px;
  margin-bottom: 0px;
}
.pwdStength-weak::-webkit-progress-value {
  background-color: #ea0906;
}
.pwdStength-fair::-webkit-progress-value {
  background-color: #f1c207;
}
.pwdStength-good::-webkit-progress-value {
  background-color: #1a80f5;
}
.pwdStength-strong::-webkit-progress-value {
  background-color: #0bc223;
}
.pwdStength-weak span {
  color: #ea0906;
}
.pwdStength-fair span {
  color: #f1c207;
}
.pwdStength-good span {
  color: #1a80f5;
}
.pwdStength-strong span {
  color: #0bc223;
}

Implement Strength Checker to Input

Now, we will create the password input field and implement the strength checker in the password strength meter component.

Make sure to add the given code to the features/PwdMeter.js file.

import React, { useState } from "react";
import PasswordStrengthChecker from "./PasswordStrengthChecker";

const PwdMeter = () => {
  const [inputVal, setInputVal] = useState({
    password: "",
  });

  const [isError, setError] = useState(null);
  const onPwdCahnge = (e) => {
    let password = e.target.value;
    setInputVal({
      ...inputVal,
      password: e.target.value,
    });
    setError(null);
    let caps, small, num, spcChar;
    if (password.length < 4) {
      setError(
        "Password must include minimum 4 characters, including 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;
      spcChar = (password.match(/\W/g) || []).length;
      if (caps < 1) {
        setError("Add atleast one UPPERCASE letter");
        return;
      } else if (small < 1) {
        setError("Add atleast one lowercase letter");
        return;
      } else if (num < 1) {
        setError("Add atleast one number");
        return;
      } else if (spcChar < 1) {
        setError("Add atleast one special character: @$! % * ? &");
        return;
      }
    }
  };

  const [isStrong, setStrongPwd] = useState(null);

  const inputHandler = async (childData) => {
    setStrongPwd(childData);
  };

  const onSubmit = async (event) => {
    try {
      event.preventDefault();
      event.persist();
      console.log(inputVal.password);
    } catch (error) {
      throw error;
    }
  };

  return (
    <div className="center">
      <h2>React Password Strength Meter Example</h2>
      <div>
        <form onSubmit={onSubmit}>
          <p htmlFor="password">
            <label><strong>Password</strong></label>
            {isError !== null && <p className="errors"> - {isError}</p>}
          </p>
          <input
            type="password"
            id="password"
            name="password"
            onChange={onPwdCahnge}
            required
          />
          <PasswordStrengthChecker
            password={inputVal.password}
            actions={inputHandler}
          />
          {isStrong === "strong" && <button type="submit"> Signup </button>}
        </form>
      </div>
    </div>
  );
};

export default PwdMeter;

Update App Component

Open the App.js file, here in this file you must import the PwdMeter component.

import React from "react";
import PwdMeter from "./features/PwdMeter";

function App() {
  return (
    <div>
      <PwdMeter />
    </div>
  );
}

export default App;

View App on Browser

From the console execute the following command, it open the app on the given url.

npm start
http://localhost:3000

How to Create Password Strength Checker in React Js

Conclusion

In this post, we have ascertained how to build a simple Password strength meter in React js without external dependency.

When a user creates the password, at-least he will have a better idea of what security shield we added to the password field.

I hope you liked this excellent password strength indicator in react js