DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. JavaScript
  4. Use RegEx to Test Password Strength in JavaScript

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.

Nic Raboy user avatar by
Nic Raboy
·
May. 16, 15 · Tutorial
Like (1)
Save
Tweet
Share
92.23K Views

Join the DZone community and get the full member experience.

Join For Free

Recently, 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.

Password strength JavaScript Strings Data Types Testing

Published at DZone with permission of Nic Raboy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Tech Layoffs [Comic]
  • Taming Cloud Costs With Infracost
  • Load Balancing Pattern
  • Top 5 PHP REST API Frameworks

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: