John Mwaniki /   26 Dec 2023

How to Do Password Strength Validation with jQuery

When building applications, safeguarding personal and sensitive information is of paramount importance.

One fundamental aspect of online security is the use of strong passwords. Strong passwords act as a robust line of defense against unauthorized access, protecting users from potential breaches.

In this article, we will cover the implementation of password strength testing and validation using jQuery.

Understanding Password Strength

Not all passwords are created equal, some are strong, while others are weak. A strong password is one that is resistant to various hacking techniques and meets specific criteria.

Generally, a strong password should be lengthy, and include a mix of uppercase and lowercase letters, numbers, and special characters. For instance, a password like "hJ@5zD8#w0[21!" is considered strong as it meets that criterion.

The complexity and randomness make it unpredictable and difficult for attackers to crack through brute-force or dictionary attacks.

Weak passwords, such as "123456", "password", or personal information like birthdates are easily susceptible to hacking attempts. Cybercriminals often exploit common and easily guessable passwords, gaining unauthorized access to sensitive information.

Strong passwords act as a deterrent, significantly reducing the likelihood of successful unauthorized access.

Implementing Password Strength Validation with jQuery

Here's a step-by-step guide to implementing a real-time password strength validation using jQuery:

Step 1: Include jQuery Library

Start by including the jQuery library in your project. You can either download it and host it locally or include it from a CDN for faster loading.

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

Step 2: Create HTML Structure

Design an HTML form that includes an input field for the password.

<form id="passwordForm">
    <label for="password">Create a Password:</label>
    <input type="password" id="password">
    <div id="passwordStrength"></div>
</form>

We have also added a div element next to the password field that will display the password strength as the user types.

Step 3: Get the Password Value on Key-up

To do a live password strength validation, we need to detect when a user releases a key when typing in the password field and get the entered value using jQuery. We can achieve this by targeting the password input field by its ID and the keyup event.

$("#password").keyup(function () {
    var password = $(this).val();
    // Implement your password strength checking logic here
});

Step 4: Implement Password Strength Logic

Next, we need to add jQuery code to implement logic to assess the strength of the password based on predefined criteria.

We will customize our criteria as below:

  • Strong Password: Is at least 8 characters in length and comprises a combination of lowercase (a-z) and uppercase letters (A-Z), numbers (0-9), and special characters (e.g., &, #, @, $, etc).
  • Medium Strength: Is at least 8 characters in length, has more than one type of character combination but doesn't include all the four types of characters.
  • Weak Password: Is less than 8 characters in length or contains only one type of character e.g. lowercase letters, uppercase letters, or numbers.

We can easily accomplish this using regular expressions in jQuery to verify the presence of different character types and dynamically update the content of the div element with the password strength.

var uppercaseLetters = /[A-Z]/;
var lowercaseLetters = /[a-z]/;
var specialCharacters = /[-._!"`'#%&,:;<>=@{}~\$\(\)\*\+\/\\\?\[\]\^\|]+/;
var numbers = /[0-9]/;

if (password.length < 8) {
    $('#passwordStrength').html("Weak password (should be atleast 8 characters).");
} 
else {
    // When the password is more than 8 characters in length
    if (password.match(numbers) && password.match(uppercaseLetters) && password.match(lowercaseLetters) && password.match(specialCharacters)) {
        /**
        * When the password contains lower and uppercase letters, numbers,
        * and special characters
        **/
        $("#passwordStrength").html("Strong password");
    }
    else if (lowercaseLetters.test(password) ^ uppercaseLetters.test(password) ^ numbers.test(password)) {
        // When the password contains only lowercase letters, uppercase letters, or numbers
        $("#passwordStrength").html("Weak password (Include upper and lowercase letters, numbers, and special characters).");
    }
    else {
        // When the password contains more than one but not all types of characters
        $("#passwordStrength").html("Medium strength (Include upper and lowercase letters, numbers, and special characters).");
    }
}

In the above code, we first check the length of the password. If it's less than 8 characters, we update the content of the div element ("#passwordStrength") to 'Weak password', with recommendations of the criteria to use.

If it has more than 8 characters, we check whether it contains lowercase letters, uppercase letters, numbers, and special characters. If it has all the types, we update the message to "Strong password".

Then we check if it comprises lowercase letters only, uppercase letters only, or numbers only. If it meets this criterion, we update the message to 'Weak password'. Else, if it doesn't meet the criteria of strong or weak, we update the message as 'Medium strength'.

Full example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Password Strength in jQuery</title>
    <style type="text/css">
        #passwordForm {
            width: 30%;
            margin: 30px auto;
        }
        #password {
            width: 100%;
            height: 35px;
            font-size: 16px;
            padding: 3px;
            margin-bottom: 10px;
        }
        #passwordStrength {
            width: 100%;
            padding: 10px;
            border-radius: 7px;
        }
        .strong {
            color: #0a3622;
            background-color: #d1e7dd;
            border: 1px solid #0a3622;
        }
        .medium {
            color: #664d03;
            background-color: #fff3cd;
            border: 1px solid #664d03;
        }
        .weak {
            color: #58151c;
            background-color: #f8d7da;
            border: 1px solid #58151c;
        }
    </style>
</head>
<body>
<form id="passwordForm">
    <label for="password">Create a Password:</label>
    <input type="password" id="password">
    <div id="passwordStrength"></div>
</form>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function () {
  $("#password").keyup(function(){
    var password = $(this).val();

    var uppercaseLetters = /[A-Z]/;
    var lowercaseLetters = /[a-z]/;
    var specialCharacters = /[-._!"`'#%&,:;<>=@{}~\$\(\)\*\+\/\\\?\[\]\^\|]+/;
    var numbers = /[0-9]/;

    if (password.length < 8) {
        $('#passwordStrength').attr("class", "weak");
        $('#passwordStrength').html("Weak password (should be atleast 8 characters).");
    } 
    else {
        if (password.match(numbers) && password.match(uppercaseLetters) && password.match(lowercaseLetters) && password.match(specialCharacters)) {
            $('#passwordStrength').attr("class", "strong");
            $('#passwordStrength').html("Strong password");
        }
        else if (lowercaseLetters.test(password) ^ uppercaseLetters.test(password) ^ numbers.test(password)) {
            $('#passwordStrength').attr("class", "weak");
            $('#passwordStrength').html("Weak password (Include upper and lowercase letters, numbers, and special characters).");

        }
        else {
            $('#passwordStrength').attr("class", "medium");
            $('#passwordStrength').html("Medium strength (Include upper and lowercase letters, numbers, and special characters).");
        }
    }
  });
}); 
</script>
</body>
</html>

Output :

In the above example, we added styling for 'weak', 'medium', and 'strong' CSS classes with different background and text colors. On validating the password, we update the class of the password strength div element with the attr() method to reflect the respective colors alongside the alert message.

You can customize the password strength validation regular expression and code as you wish depending on your specifications.

Conclusion

A strong password is a cornerstone of online security. Implementing password strength validation enhances the security of web applications by guiding users to create strong passwords.

By educating users on what constitutes a strong password and providing real-time feedback, you can contribute to a safer online environment. In this article, you have learned how to do real-time password strength validation using jQuery.