Strong password validation using JavaScript

Here we will see how to create strong password validation using JavaScript. For strong validation i mentioned here the condition is at least one capital letter and one small letter and one number and one special character then it shows the strong password and also i mentioned here the minimum character length should be 8 character using html5 pattern.

In this example we are going to get all character using array then will display the validation message along with color using switch case in JavaScript. I hope this simple example will help you. This example having the demo page also, have a look.



Strong Password validation using JavaScript:

<!DOCTYPE html>

<html>

<head>

<title>Strong password validation using Javascript</title>

<script>

function validatePassword(password) {

// Do not show anything when the length of password is zero.

if (password.length === 0) {

document.getElementById("msg").innerHTML = "";

return;

}

// Create an array and push all possible values that you want in password

var matchedCase = new Array();

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

matchedCase.push("[A-Z]");      // Uppercase Alpabates

matchedCase.push("[0-9]");      // Numbers

matchedCase.push("[a-z]");     // Lowercase Alphabates

// Check the conditions

var ctr = 0;

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

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

ctr++;

}

}

// Display it

var color = "";

var strength = "";

switch (ctr) {

case 0:

case 1:

case 2:

strength = "Very Weak";

color = "red";

break;

case 3:

strength = "Medium";

color = "orange";

break;

case 4:

strength = "Strong";

color = "green";

break;

}

document.getElementById("msg").innerHTML = strength;

document.getElementById("msg").style.color = color;

}

</script>

<style>

.san-div6

{

max-width: 450px;

width:100%;

margin: 0 auto;

background-color: #d5dcff;

padding: 80px 30px;

border: 3px solid #aab5e8;

border-radius: 6px;

}

input#pwd {

width: 100%;

height: 30px;

border: 1px solid #6571ad;

border-radius: 5px;

font-size: 18px;

padding:10px;

}

input[type="submit"] {

background-color: #1a2f98;

color: #fff;

padding: 7px 25px;

display: block;

margin: 0 auto;

font-size: 18px;

border: 1px solid #1a2f98;

}

h1{

font-size:28px;

}

#msg

{

line-height: 34px;

}

</style>

</head>

<body>

<div class="san-div6">

<h1 style="text-align:center"><strong>Strong password validation using JavaScript</strong></h1>

<form action="http://www.sanwebcorner.com">

<input type="text" id="pwd" placeholder="Password" required  pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" onkeyup="validatePassword(this.value);"/><span id="msg"></span><br/><br/>

<input type="submit" value="Submit">

</form>

</div>

</body>

</html>

Post a Comment

0 Comments