In this tutorial, we are going to validate password strength using jQuery. We have regex patterns for alphabets numbers and special characters. Password text will be matched with this pattern. Then, its strength will be validated based on the type of characters it contains.
This form interface is used to enter our password to be checked for validating its strength.
<div class="phppot-container tile-container">
<h2 class="text-center">Password Strength Checker</h2>
<form>
<div class="row">
<label>Password:</label> <input type="password"
name="password" id="password" class="full-width"
onkeyup="checkPasswordStrength();" />
</div>
<div id="password-strength-status"></div>
</form>
</div>
This function will be called on the key-up event of the password field. This function checks the length of the password text. If it is less than 6 characters, then it will be validated as the weak password.
If not, the password will be matched with the regex patterns. If the password contains at least one alphabet, one number, and one special character then it will be considered as the strong password.
function checkPasswordStrength() {
var number = /([0-9])/;
var alphabets = /([a-zA-Z])/;
var special_characters = /([~,!,@,#,$,%,^,&,*,-,_,+,=,?,>,<])/;
var password = $('#password').val().trim();
if (password.length < 6) {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('weak-password');
$('#password-strength-status').html("Weak (should be atleast 6 characters.)");
} else {
if (password.match(number) && password.match(alphabets) && password.match(special_characters)) {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('strong-password');
$('#password-strength-status').html("Strong");
}
else {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('medium-password');
$('#password-strength-status').html("Medium (should include alphabets, numbers and special characters.)");
}
}
}