DEV Community

Shantanu
Shantanu

Posted on

Password strength validation

Define your password strength complexity requirements with ease.

eg. Password must be at least 9 chars, 2 uppercase, 3 lowercase, 2 digit, 2 special char, no more than 2 same consecutive chars, no more than 3 consecutive ascending digits, no more than 3 consecutive descending digits.

I have built libraries in:

  • .NET
  • .NET MAUI
  • TypeScript
  • Angular
  • ReactJS

to support this.

Under the covers, it uses Regular Expressions.

Setting the strength options is really easy.

Below is an example of using the ReactJS library:

import React, { useState } from 'react'
import { MaximumNoOfConsecutiveDigits, MyPasswordStrengthOptions, PasswordStrength } from 'react-my-password-strength'

const App = () => {
  const [formData, setFormData] = useState({});
  const [formValid, setFormValid] = useState(false);

  const [error, setError] = useState("");

  const handleOnValidation = (name:string, value:string, isValid:boolean|null) => {
    if (!isValid && (value === null || value === '')) {
      console.log("Password is empty, skipping validation.");
      setError("");
      setFormValid(false);
      return;
    }

    setError(isValid ? "" : "Password must be at least 9 chars, 2 uppercase, 3 lowercase, 2 digit, 2 special char, no more than 2 same consecutive chars, no more than 3 consecutive ascending digits, no more than 3 consecutive descending digits");

    setFormData((prev) => ({ ...prev, [name]: value }));
    // Check if all fields are valid
    setFormValid(isValid === true && Object.values(formData).every((v) => v));
  };

  const handleSubmit = (e: { preventDefault: () => void; }) => {
    e.preventDefault();
    if (formValid) {
      alert("Form submitted successfully!");
      console.log("Form Data:", formData);
    } else {
      alert("Please fix validation errors before submitting.");
    }
  };


  return (
    <form onSubmit={handleSubmit}>
        <div style={{padding: "20px" }}>
          <div style={{marginRight: "20px" }}>
            <label htmlFor="password" style={{ display: "block", fontWeight: "bold" }}>
              Password
            </label>
            <br />
            <PasswordStrength
                name='password'
                placeholder='Please enter your password'
                strengthOptions={getOptions()}
                initialStyleOptions={initialStyleOptions} 
                styleOptions={styleOptions}                 
                errorStyleOptions={errorStyleOptions}
                onValidation={handleOnValidation}
            />
            <span style={{ color: "red", fontSize: "12px" }}>{error}</span>
          </div>            
          <br />
          <button type="submit" disabled={!formValid} style={{ marginTop: "10px", padding: "8px 16px" }}>
            Submit
          </button>
        </div>
    </form>
  )
}

export default App

// Configure password strength requirements
function getOptions(): MyPasswordStrengthOptions {
  let options = new MyPasswordStrengthOptions();

  options.minimumLength = 8;
  options.requireUppercase = true;
  options.minimumUppercase = 2;
  options.requireLowercase = true;
  options.minimumLowercase = 3;
  options.requireDigit = true;
  options.minimumDigit = 2;
  options.requireSpecialCharacter = true;
  options.minimumSpecialCharacter = 2;
  options.requireMaxNoOfSameConsecutiveCharacters = true;
  options.maximumNoOfSameConsecutiveCharacters = 2;
  options.requireMaximumNoOfConsecutiveAscendingDigits = true;
  options.maximumNoOfConsecutiveAscendingDigits = MaximumNoOfConsecutiveDigits.Three;
  options.requireMaximumNoOfConsecutiveDescendingDigits = true;
  options.maximumNoOfConsecutiveDescendingDigits = MaximumNoOfConsecutiveDigits.Three;

  return options;
}

const initialStyleOptions={
  border: "1px solid #ccc",
  padding: "8px",
  width: "100%"
}

const styleOptions={
  border: "2px solid green",
  padding: "8px",
  width: "100%"
}

const errorStyleOptions={
  border:"2px solid red",
  padding: "8px",
  width: "100%"
}
Enter fullscreen mode Exit fullscreen mode

Initial

Initial

Invalid

Invalid

Valid

Valid

Take a look at my project on GitHub.

GitHub logo VeritasSoftware / PasswordStrengthDataAnnotation

A password strength data annnotation for asp net core.

MyPasswordStrength

.NET Build & Test TypeScript Build & Test Angular Build & Test ReactJS Build & Test

Packages Version Downloads
MyPasswordStrength Nuget Version Downloads count
ts-my-password-strength NPM Version Downloads count
angular-my-password-strength NPM Version Downloads count
react-my-password-strength NPM Version Downloads count

Typescript Library Angular Library ReactJS Library .NET MAUI Library

Define your password strength complexity requirements with ease using the library.

The package provides a Validator class that you can use to validate passwords programmatically.

Programmatic Password Validation

You can validate passwords programmatically using the PasswordStrengthValidator class provided in the package.

You can set the password strength requirements through the properties of the PasswordStrengthValidator class,

and then call the PasswordStrength method to check if a given password meets those requirements.

The PasswordStrength method returns a boolean indicating whether the password is valid according to the configured requirements.

Sample Usage

// Configure password strength requirements
var validator = new PasswordStrengthValidator
{
    MinimumLength = 8,
    RequireUppercase = true,
    MinUppercase = 2,
    RequireLowercase = true,
    MinLowercase = 3,
    RequireDigit = true,
    MinDigit = 2,
    RequireSpecialCharacter = true,
    MinSpecialCharacter
Enter fullscreen mode Exit fullscreen mode

Top comments (0)