How to Check if Password is Strong or Weak using Javascript

In this tutorial, you will learn how to check if password entered by user is strong or weak.  This is very common practice which every website developer follow to make sure password entered by user is strong enough .We are going to use our own custom logic to verify if password is strong or not.  You can simply take this code and modify it to fit your need. HTML, javascript and CSS code is given below.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <input type="text" placeholder="Enter Password">
        <button>Check</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>

CSS:

div {
    display: flex;
    flex-direction: column;
    align-items: center;
}

input, button{
    padding: 5px 10px;
    margin: 5px;
}

Javascript:

let btnCheck = document.querySelector('button');
let input = document.querySelector('input');
let result = document.querySelector('h1');


let maxLength = 20;
let minLength = 10;

let lowerMinCount = 3;
const LOWER_REGEX = /([a-z])/g;

let upperMinCount = 3;
const UPPER_REGEX = /([A-Z])/g;

let numMinCount = 2;
const NUM_REGEX = /([\d])/g;

let specialMinCount = 2;
const SPECIAL_REGEX = /([$&+,:;=?@#|'<>.^*()%!-])/g;

btnCheck.addEventListener('click', () => {

    let password = input.value;

    if(password.length > maxLength){
        result.innerText = "Password should be less than 20 characters";
        return;        
    }

    result.innerText = isStrongPassword(password) ? 'STRONG' : 'WEAK';

});


function isStrongPassword(password) {
    let upperMatch = password.match(UPPER_REGEX) ?? [];
    let lowerMatch = password.match(LOWER_REGEX) ?? [];
    let numMatch = password.match(NUM_REGEX) ?? [];
    let specialMatch = password.match(SPECIAL_REGEX) ?? [];

    return password.length >= minLength &&
    upperMatch.length >= upperMinCount &&
    lowerMatch.length >= lowerMinCount &&
    numMatch.length >= numMinCount &&
    specialMatch.length >= specialMinCount
}

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •