Just the weekly tutorials.

Creating a script that verifies password strength in JavaScript

Password strength indicator is a useful reminder to the user who is signing up for your website. A strong password decreases the chances of someone breaking into your online account by guessing it.

Note: You can use jQuery's .on() method to bind a function to multiple events by separating them using the space character as shown in the following example:
$("input#password").on("keyup keydown", function() { /*...*/ });

This jQuery technique can be used with any other JavaScript event, it's not limited to passwords. To learn more about events follow this article The basics of jQuery Events.

We will get to the source code in just a moment. For now let's take a look at an example of how it works. Try typing a password into the following input box:

Password: Your password is empty.

Using password strength test to create a stronger password does not guarantee that the password cannot be broken and should not be used as the only safety measure against password cracking. However, because a password that is easy to remember is also easy to guess, being mindful of your password strength when signing up for an online account is a plus.

What makes passwords strong or weak?

First, let's define a few rules that the password strength verification script, when followed, will consider the password a little more secure or stronger. This depends on several factors such as password length and the presence of special characters:

An example of a weak password is mypwd1 because it is easy to guess.

An example of a strong password is MyPwd125$ because it is hard to guess.

Because when a password is cracked it is usually done so by guessing, being mindful of these points allows us to increase the average number of tries (or guesses) it would take for someone to guess your password.

Using JavaScript to create password strength verification script

Using JavaScript we can create a simple password strength verification script. First we need to intercept the onkeyup and onkeydown events associated with the password input element. This can be done using HTML tag attributes with two aforementioned names, but we can also create a jQuery script that takes care of that.

We can then automatically attache a password verification bar just after the password input element using a span element. You can re-design it to whatever you wish or add custom colored bars with a message like "weak password", "strong password", etc. that would appear based on the calculated strength.

Note: inside the on() method the this variable refers to the raw JavaScript object which was selected using the CSS selector(in this case input#password.) The this variable will be equivalent to document.getElementById("password"); You can learn more about JavaScript's this variable by following this link.

The following example assumes that jQuery is added to your web page.

$(document).ready(function(){ // select the INPUT password element, // and attach keyup and keydown events to it $("input#password").on("keyup keydown", function(msg) { var password = $(this).val(); // Calculate strength var strength = 0; var points = 20; // points per test var pattern1 = /[A-Z]/g; // Contains uppercase letters var pattern2 = /[a-z]/g; // Contains lowercase letters var pattern3 = /[0-9]/g; // Contains digits var pattern4 = /[~`!@#$%^&*_+-]/g; // Contains a special character if (password.length >= 7) { strength += points; } if (password.match(pattern1) != null) { strength += points; } if (password.match(pattern2) != null) { strength += points; } if (password.match(pattern3) != null) { strength += points; } if (password.match(pattern4) != null) { strength += points; } if (password == "") { $("#strength").text("Your password is empty."); } else { var message = ["Easy to guess", "Weak", "Average", "Strong", "Very strong"]; var index = (strength - 20) / 20; if (index == -1) $("#strength").text("Easy to guess"); else $("#strength").text(message[index]); } }); });

This piece of code uses Regular Expressions (RegEx) to test the password value being entered. After doing 5 tests (outlined in a previous section "What makes a password strong or weak") the appropriate strength message is shown inside a span HTML element.

You can learn more about Regular Expressions(Regex) and jQuery in this article.

Because there are 5 tests, each time a tests is passed, we add 20 to the strength variable. This way when all 5 tests are complete, we have a full 100 percent strength. In this code this value is called strength points. You can add more tests yourself, and decide the amount of points each test would produce. Simply divide the total possible score by the number of tests. For example if there were only 4 tests, the points per test would be 25 (25 times 4 is 100.)

In this code you will also notice some basic score to array index calculations to arrive at a text-based message (weak,strong,etc) which lets the user know the strength of the password they have entered.

These text values are displayed instead of numbers. For example a score of 20 is equal to text string "Weak". A score of 40 equals "Average" and so forth. To match the score with the actual array values which start with index 0 (0,1,2,3,4 in this example) I had to divide the resulting strength score by 20.

Optimizing password strength checker

Update: June 14th, 2013: A tutorial newsletter subscriber has brought up one inconsistency with the current password checker code.

Let's consider the following passwords:

That can't be right. In first example, the password strength checker values the variety of characters over its length. In the second example, a very long password which would take months to guess is still "weak."

The solution to the first problem lies in the following JavaScript code example, where a password whose length is less than 7 characters will not perform any tests related to the length of the password.

if (password.length < 7) { /* Consider the password "short" */ } else { /* Do additional tests */ }

But it would probably be proper to give at least some credit to special characters nonetheless. In order to do this we can check for password's length, not during, but at the end of all other tests and subtract a value that equals 1 unit of "points per test" value (20 in our case) from the total password strength score when the password value is not long enough.

if (password.length < 7) { strength -= points; }

And to cover the long passwords regardless of whether they contain special characters the script can check its length past 7 characters. But we don't want to add points per single character. We want to add points every 4 characters if the length is longer than 7.

For example 7 + 4 = 11 adds 20 points to the overall strength of the password because there are at least 4 characters past 7. The value of 7 + 4 + 4 = 23 would produce 40 points because there are 8 characters past 7, and so forth. You can choose your own value other than 4 for each span, but I think it is balanced enough given other circumstances.

The script will multiply points every 4 characters. Identifying how many times a 4-character span ("abcd", or "fhw2" for example) fits into the length of the password can be achieved using the little-known modulus operator (or modulo operator) which in JavaScript is represented by the percent symbol.

The modulus operator will tell us the remainder of what did not fit into the base number. For example, 8 % 4 is 0 because 4 fits into 8 perfectly without a remainder. But 7 % 4 equals 3 because 4 only fully fits once into seven and the remainder is 3. Let's take a look at a few modulo examples:

var m = 8 % 4; // 0 var n = 9 % 3; // 0 var o = 5 % 2; // 1 var p = 7 % 4; // 3

In a modulo expression 5 % 2, 5 is known as the divisor and 2 is the divider. 5 % 2 results in 1 because 2 fits twice into 5 (2 * 2 + 1 = 5). Notice that we had to add 1 to arrive at 5. That is the modulo, it is the remainder. The remainder is always less than the divisor (1 in this case, is less than 2.) If it hadn't been less than the divisor, it would fit into the divider.

// How many times does 4 fit into the password's length var len = password.length - 7; if (len > 0) { // How many spans of 4 characters are there past len=7? var spans = (len - len % 4) / 4; // Update the password strength value strength += spans * 20; }

Remember that we are trying to solve the problem of a long password which does not contain any special characters. We consider a password whose length is less than 7 characters not long enough.

This script will count the number of 4-character spans past the point of 7 characters. This is why we subtract 7 from the total length of the password.

If length of the password is still greater than 0 after we subtract 7, then we are ready to start counting the spans. Also remember that modulo returns a remainder. If we subtract it from the length, and divide it by the divisor, we get the number of spans fitting into the value. That's what the modulo operator is used for in this example.

Knowing all this, finally we can come up with the following script:

/* Once the RegEx tests are completed, do the following... */ if (password.length < 7) strength -= points; else if (password.strength > 7) { var len = password.length - 7; if (len > 0) { var spans = (len - len % 4) / 4; strength += spans * 20; } } // Prevent the password strength from growing wild if (strength > 100) strength = 100;

Password strength checker HTML

And finally, we need to define some basic HTML to work with our password strength checker script. Of course, yours could be anything you want and you can even add your own CSS styles (red,orange,green?) based on the returned values for "weak", "strong", etc.

The following is the HTML including the input box that will store the password and its accompanying strength message which will be automatically updated every time a key is pressed down or released.

<input id = "password" type = "password"/> <span id = "strength">Your password is empty</span>

Just the weekly tutorials.