How to check password strength using javascript


index.php


     

<!DOCTYPE html>

<html lang="en">

<meta charset="utf-8"> 

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Strong Password Validation using Javascript</title>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container" style="margin-top:50px;">

 <div class="row">

  <div class="col-sm-3"></div>

   <div class="col-sm-6">

   <label>Password</label>

   <div>

   <input name="password" id="password" type="password" class="form-control" placeholder="Enter your password..." value="" onkeyup="CheckPasswordStrength()"  required="required" />

   </div> 

   	<span id="password_strength"></span>

    <div class="row" style="margin-top:20px;">

      <ol>

        <li>At least one capital letter</li>

        <li>At least one special Character</li>

      </ol>

    </div>

   </div>

    <div class="col-sm-3"></div>

 </div>

</div>

</body>

</html>

     

    

custom.js


     

<script>

/*--Check password Strenght script start--*/

function CheckPasswordStrength() {

	var password_strength = document.getElementById("password_strength");

	var password = document.getElementById('password').value;

	//TextBox left blank.

	if (password.length == 0) {

		password_strength.innerHTML = "";

		return;

	}

	//Regular Expressions.

	var regex = new Array();

	regex.push("[A-Z]"); //Uppercase Alphabet.

	regex.push("[a-z]"); //Lowercase Alphabet.

	regex.push("[0-9]"); //Digit.

	regex.push("[$@$!%*#?&]"); //Special Character.

	var passed = 0;

	//Validate for each Regular Expression.

	for (var i = 0; i < regex.length; i++) {

		if (new RegExp(regex[i]).test(password)) {

			passed++;

		}

	}

	//Validate for length of Password.

	if (passed > 2 && password.length > 8) {

		passed++;

	}



	//Display status.

	var color = "";

	var strength = "";

	switch (passed) {

		case 0:

		case 1:

			strength = "<strong>Weak</strong>";

			color = "red";

			break;

		case 2:

			strength = "<strong>Good</strong>";

			color = "darkorange";

			break;

		case 3:

		case 4:

			strength = "<strong>Strong</strong>";

			color = "green";

			break;

		case 5:

			strength = "<strong>Very Strong</strong>";

			color = "darkgreen";

			break;

	}

	password_strength.innerHTML = strength;

	password_strength.style.color = color;

}

/*---Check password strenght script End----*/			

</script>