Check Password Strength with JavaScript or jQuery and Regular Expressions (With Server-Side Examples, Too!)
I was doing some research on finding a good example of a Password Strength checker that uses JavaScript and Regular Expressions (Regex). In the application at my work, we do a post back to verify the password strength and it’s quite inconvenient for our users.
What is Regex?
A regular expression is a sequence of characters that define a search pattern. Usually, such patterns are used by string searching algorithms for find or find and replace operations on strings, or for input validation.
This article is definitely not to teach you regular expressions. Just know that the ability to use Regular Expressions will absolutely simplify your development as you search for patterns in text. It’s also important to note that most development languages have optimized regular expression use… so rather than parsing and searching strings step-by-step, Regex is typically much faster both server and client-side.
I searched the web quite a bit before I found an example of some great Regular Expressions that look for a combination of length, characters, and symbols. However, the code was a little excessive for my taste and tailored for .NET. So I simplified the code and put it in JavaScript. This makes it validate the password strength in real-time on the client’s browser before posting it back… and provides some feedback to the user on the password’s strength.
Type A Password
With each stroke of the keyboard, the password is tested against the regular expression and then feedback is provided to the user in a span beneath it.
JavaScript Password Strength Function
The Regular Expressions do a fantastic job of minimizing the length of the code. This JavaScript function checks the strength of a password and whether foiling it is easy, medium, difficult, or extremely difficult to guess. As the person types, it displays tips on encouraging it to be stronger. It validates the password based on:
- Length – If the length is under or over 8 characters.
- Mixed Case – If the password has both upper and lower case characters.
- Numbers – If the password includes numbers.
- Special Characters – If the password includes special characters.
The function displays the difficulty as well as some tips on hardening the password further.
function checkPasswordStrength(password) {
// Initialize variables
var strength = 0;
var tips = "";
// Check password length
if (password.length < 8) {
tips += "Make the password longer. ";
} else {
strength += 1;
}
// Check for mixed case
if (password.match(/[a-z]/) && password.match(/[A-Z]/)) {
strength += 1;
} else {
tips += "Use both lowercase and uppercase letters. ";
}
// Check for numbers
if (password.match(/\d/)) {
strength += 1;
} else {
tips += "Include at least one number. ";
}
// Check for special characters
if (password.match(/[^a-zA-Z\d]/)) {
strength += 1;
} else {
tips += "Include at least one special character. ";
}
// Return results
if (strength < 2) {
return "Easy to guess. " + tips;
} else if (strength === 2) {
return "Medium difficulty. " + tips;
} else if (strength === 3) {
return "Difficult. " + tips;
} else {
return "Extremely difficult. " + tips;
}
}
If you’d like to update the color of the tip, you can do that as well by updating the code after the // Return results
line.
// Get the paragraph element
var strengthElement = document.getElementById("passwordStrength");
// Return results
if (strength < 2) {
strengthElement.textContent = "Easy to guess. " + tips;
strengthElement.style.color = "red";
} else if (strength === 2) {
strengthElement.textContent = "Medium difficulty. " + tips;
strengthElement.style.color = "orange";
} else if (strength === 3) {
strengthElement.textContent = "Difficult. " + tips;
strengthElement.style.color = "black";
} else {
strengthElement.textContent = "Extremely difficult. " + tips;
strengthElement.style.color = "green";
}
jQuery Password Strength Function
With jQuery, we don’t actually have to write the form with an oninput update:
<form>
<label for="password">Enter password:</label>
<input type="password" id="password">
<p id="password-strength"></p>
</form>
We can also modify the color of the messages if we’d like.
$(document).ready(function() {
$('#password').on('input', function() {
var password = $(this).val();
var strength = 0;
var tips = "";
// Check password length
if (password.length < 8) {
tips += "Make the password longer. ";
} else {
strength += 1;
}
// Check for mixed case
if (password.match(/[a-z]/) && password.match(/[A-Z]/)) {
strength += 1;
} else {
tips += "Use both lowercase and uppercase letters. ";
}
// Check for numbers
if (password.match(/\d/)) {
strength += 1;
} else {
tips += "Include at least one number. ";
}
// Check for special characters
if (password.match(/[^a-zA-Z\d]/)) {
strength += 1;
} else {
tips += "Include at least one special character. ";
}
// Update the text and color based on the password strength
var passwordStrengthElement = $('#password-strength');
if (strength < 2) {
passwordStrengthElement.text("Easy to guess. " + tips);
passwordStrengthElement.css('color', 'red');
} else if (strength === 2) {
passwordStrengthElement.text("Medium difficulty. " + tips);
passwordStrengthElement.css('color', 'orange');
} else if (strength === 3) {
passwordStrengthElement.text("Difficult. " + tips);
passwordStrengthElement.css('color', 'black');
} else {
passwordStrengthElement.text("Extremely difficult. " + tips);
passwordStrengthElement.css('color', 'green');
}
});
});
Hardening Your Password Request
It’s essential that you don’t just validate the password construction within your JavaScript. This would enable anyone with browser development tools to bypass the script and use whatever password they’d like. You should ALWAYS utilize a server-side check to validate the password strength before storing it in your platform.
PHP Function For Password Strength
function checkPasswordStrength($password) {
// Initialize variables
$strength = 0;
// Check password length
if (strlen($password) < 8) {
return "Easy to guess";
} else {
$strength += 1;
}
// Check for mixed case
if (preg_match("/[a-z]/", $password) && preg_match("/[A-Z]/", $password)) {
$strength += 1;
}
// Check for numbers
if (preg_match("/\d/", $password)) {
$strength += 1;
}
// Check for special characters
if (preg_match("/[^a-zA-Z\d]/", $password)) {
$strength += 1;
}
// Return strength level
if ($strength < 2) {
return "Easy to guess";
} else if ($strength === 2) {
return "Medium difficulty";
} else if ($strength === 3) {
return "Difficult";
} else {
return "Extremely difficult";
}
}
Python Function For Password Strength
def check_password_strength(password):
# Initialize variables
strength = 0
# Check password length
if len(password) < 8:
return "Easy to guess"
else:
strength += 1
# Check for mixed case
if any(char.islower() for char in password) and any(char.isupper() for char in password):
strength += 1
# Check for numbers
if any(char.isdigit() for char in password):
strength += 1
# Check for special characters
if any(not char.isalnum() for char in password):
strength += 1
# Return strength level
if strength < 2:
return "Easy to guess"
elif strength == 2:
return "Medium difficulty"
elif strength == 3:
return "Difficult"
else:
return "Extremely difficult"
C# Function For Password Strength
public string CheckPasswordStrength(string password) {
// Initialize variables
int strength = 0;
// Check password length
if (password.Length < 8) {
return "Easy to guess";
} else {
strength += 1;
}
// Check for mixed case
if (password.Any(char.IsLower) && password.Any(char.IsUpper)) {
strength += 1;
}
// Check for numbers
if (password.Any(char.IsDigit)) {
strength += 1;
}
// Check for special characters
if (password.Any(ch => !char.IsLetterOrDigit(ch))) {
strength += 1;
}
// Return strength level
if (strength < 2) {
return "Easy to guess";
} else if (strength == 2) {
return "Medium difficulty";
} else if (strength == 3) {
return "Difficult";
} else {
return "Extremely difficult";
}
}
Java Function For Password Strength
public String checkPasswordStrength(String password) {
// Initialize variables
int strength = 0;
// Check password length
if (password.length() < 8) {
return "Easy to guess";
} else {
strength += 1;
}
// Check for mixed case
if (password.matches(".*[a-z].*") && password.matches(".*[A-Z].*")) {
strength += 1;
}
// Check for numbers
if (password.matches(".*\\d.*")) {
strength += 1;
}
// Check for special characters
if (password.matches(".*[^a-zA-Z\\d].*")) {
strength += 1;
}
// Return strength level
if (strength < 2) {
return "Easy to guess";
} else if (strength == 2) {
return "Medium difficulty";
} else if (strength == 3) {
return "Difficult";
} else {
return "Extremely difficult";
}
}
And if you’re just looking for a great password generator, I’ve built a nice little online tool for that.