Simple Password Strength Meter with jQuery

People generally do not realise the power of regular expressions. If utilised at right places, regular expressions can be very helpful. In this post I will show you how to use regular expressions in JavaScript to measure the password strength. Client side password meter can be very helpful for interactive web applications. Lets take a look at it.




Live Demo Download Script

jQuery Code

<script language="javascript">
$(document).ready(function()
{
$('#password').keyup(function()
{
return passwordChanged();
});
});
function passwordChanged()
{
var strength = document.getElementById('strength');
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
var pwd = document.getElementById("password");
if (pwd.value.length==0)
{
$('#strength').animate({width:'50px'}, 'slow').css('backgroundColor','red');
$('#password').css('borderColor','red');
}
else if (false == enoughRegex.test(pwd.value))
{
$('#strength').animate({width:'50px'}, 'slow').css('backgroundColor','red');
$('#password').css('borderColor','red');
}
else if (strongRegex.test(pwd.value))
{
$('#strength').animate({width:'150px'}, 'slow').css('backgroundColor','green');
$('#password').css('borderColor','green');
}
else if (mediumRegex.test(pwd.value))
{
$('#strength').animate({width:'100px'}, 'slow').css('backgroundColor','yellow');
$('#password').css('borderColor','yellow');
}
else
{
$('#strength').animate({width:'50px'}, 'slow').css('backgroundColor','red');
$('#password').css('borderColor','red');
}
}
</script>

Html Code

<html>
<head>
<title>Webspeaks.in</title>
<style>
*{margin:5px; font-family:verdana;}
#password{border:2px solid #6c6c6c;padding:3px;}
#strength{height:20px;float:left; display:none;}
</style>
</head>
<body>
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Password : </td><td><input name="password" id="password" type="text" size="25" /></td>
</tr>
<tr>
<td colspan="2"><div id="strength"></div></td>
</tr>
<tr>
<td colspan="2"><small>Hints:</small></td>
</tr>
<tr>
<td colspan="2"><small>Strong : $#%$534fEWR44</small></td>
</tr>
</table>
</body>
</html>

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/