Use RegEx to Test Password Strength in JavaScript
In this post, we learn how to combine JavaScript and RegEx to create scripts that can help us test our password strength.
Join the DZone community and get the full member experience.
Join For FreeRecently, one of my Twitter followers asked me how they might validate password strength using regular expressions (RegEx) in their code.
Regular expressions via Wikipedia:
A sequence of characters that forms a search pattern, mainly for use in pattern matching with strings, or string matching.
RegEx is nice because you can accomplish a whole lot with very little. In this case, we are going to check various aspects of a string and see if it meets our requirements, being a strong or medium strength password.
In this example, I’m going to use a mixture of AngularJS and vanilla JavaScript. Basically, the JavaScript will do all the heavy lifting and the AngularJS code will be responsible for binding it all to the screen.
To show the password strength to the user, we’re going to use a rectangle that contains a color. We’ll say that a red rectangle holds a weak password, orange medium, and green a strong password. The HTML behind this would look something like the following:
<html>
<body ng-app="myapp">
<div ng-controller="PasswordController">
<div style="float: left; width: 100px">
<input type="text" ng-model="password" style="width: 100px; height: 25px" />
</div>
<div ng-style="passwordStrength"></div>
</div>
</body>
</html>
The above code has an input box and a rectangular div
tag. There is, however, a few pieces of AngularJS code that we’ll see in a moment.
The passwordStrength
variable that you see in the ng-style
tag holds all the styling information for the strength rectangle. The style information we’re going to use is as follows:
$scope.passwordStrength = {
"float": "left",
"width": "100px",
"height": "25px",
"margin-left": "5px"
};
Moving beyond the basic AngularJS stuff, let's get down to the good stuff. We’re going to make use of two different RegEx validation strings. One string will represent what is required for creating a strong password and the other will represent what is necessary for creating a medium strength password. If neither expressions are satisfied, we’ll assume it is of poor strength.
var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
Above you can see the expression for validating a strong password. Let’s break down what it is doing.
RegEx | Description |
---|---|
^ | The password string will start this way. |
(?=.*[a-z]) | The string must contain at least 1 lowercase alphabetical character. |
(?=.*[A-Z]) | The string must contain at least 1 uppercase alphabetical character. |
(?=.*[0-9]) | The string must contain at least 1 numeric character. |
(?=.*[!@#\$%\^&\*]) | The string must contain at least one special character, but we are escaping reserved RegEx characters to avoid conflict. |
(?=.{8,}) | The string must be eight characters or longer. |
That wasn’t so bad! So how about our medium strength validator? There is less precision in this one, thus making it necessary to create a more complex regular expression.
var mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");
The expression is nearly the same as the strong condition, except this time we’re including an or condition. We essentially want to label a password as having medium strength if it contains six characters or more and has at least one lowercase and one uppercase alphabetical character or has at least one lowercase and one numeric character or has at least one uppercase and one numeric character. We’ve chosen to leave special characters out of this one.
Finally, we need a way to track input on the input field. This will be handled through AngularJS by using the ngChange directive. By placing ng-change="analyze(password)"
in the input tag it will call the analyze(value)
method every time a key-stroke happens. That’s when we call our RegEx validators.
Here is the full code if you’d like to see it all put together:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
var myApp = angular.module("myapp", []);
myApp.controller("PasswordController", function($scope) {
var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
var mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");
$scope.passwordStrength = {
"float": "left",
"width": "100px",
"height": "25px",
"margin-left": "5px"
};
$scope.analyze = function(value) {
if(strongRegex.test(value)) {
$scope.passwordStrength["background-color"] = "green";
} else if(mediumRegex.test(value)) {
$scope.passwordStrength["background-color"] = "orange";
} else {
$scope.passwordStrength["background-color"] = "red";
}
};
});
</script>
</head>
<body ng-app="myapp">
<div ng-controller="PasswordController">
<div style="float: left; width: 100px">
<input type="text" ng-model="password" ng-change="analyze(password)" style="width: 100px; height: 25px" />
</div>
<div ng-style="passwordStrength"></div>
</div>
</body>
</html>
Conclusion
Regular expressions are quite powerful and if you can master them, they will save you a ton of coding time. Instead of parsing through the string using tokens or some other nonsense we managed to validate our string using a single line of code.
Published at DZone with permission of Nic Raboy, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments