Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Test Password Strength with RegEx in a React Application

TwitterFacebookRedditLinkedInHacker News

While some organizations think it is up to the user to protect themselves by choosing strong usernames and passwords, the developer can help influence good password choices by including it in the design of the application. For example, the developer could include bars, percentages, or colors to help dictate quality of a password as the user enters it into a form.

A lot of us know a weak password is short and contains either alpha or numeric, but never both. We also know strong passwords include symbols as well as variations of character case-sensitivity. So how can we check for these things in the application?

In this tutorial we’re going to make use of regular expressions to test the quality of a password. This is going to be done with simple JavaScript in a React application.

To get an idea of what we want to accomplish, take a look at the animated image:

Password RegEx Analyzer with React

In our example the background color will change as the password strength changes. The strength will be defined by several different regular expression test scenarios.

If you’ve been following the blog for a while, you might remember a similar example I did with AngularJS many years ago.

Creating a React Application for the Web

To keep this tutorial simple and easy to understand, we’re going to create a fresh project with the React CLI tool. Execute the following command to create a new project:

npx create-react-app example-project

The above command will create an example-project directory with various boilerplate files. If you have the create-react-app CLI tool installed, you can skip the npx part of the command.

Open the project’s src/App.js file and include the following code:

import React from "react";

class App extends React.Component {
    render() {
        return (
            <div>
                <!-- Logic Here... -->
            </div>
        );
    }
}

export default App;

Essentially we’ve removed a lot of the boilerplate code that came in the src/App.js file. Remember, the goal is to keep this project simple so it is easy to understand.

The core functionality of this project will exist in its own component.

Create a src/components directory within the project and create a passwordstrength.js file as well as a passwordstrength.css file within that directory.

Add the following boilerplate code to the src/components/passwordstrength.js file:

import React from "react";
import "./passwordstrength.css";

class PasswordStrength extends React.Component {

    constructor() {
        super();
        this.state = {}
    }

    render() {
        return ();
    }

}

export default PasswordStrength;

We’ll populate this file with functional code in the next step. Before we start adding our core logic, we need to add the PasswordStrength class to our src/App.js file. The file should be updated to look like the following:

import React from "react";
import PasswordStrength from "./components/passwordstrength";

class App extends React.Component {
    render() {
        return (
            <div>
                <PasswordStrength></PasswordStrength>
            </div>
        );
    }
}

export default App;

When we finally wish to render the application, we will only show what’s in the PasswordStrength class. You could make changes however you feel is appropriate after understanding the example.

Testing Password Strength with RegEx

With our project created and all the necessary files in place, now we can start adding the core logic to the application. Open the project’s src/components/passwordstrength.js file and include the following:

import React from "react";
import "./passwordstrength.css";

class PasswordStrength extends React.Component {

    constructor() {
        super();
        this.state = {
            backgroundColor: "#4285F4"
        }
        this.analyze = this.analyze.bind(this);
    }

    analyze(event) {}

    render() {
        return (
            <div style={{ backgroundColor: this.state.backgroundColor }}>
                <p><label for="password">Password: </label></p>
                <p><input type="text" name="password" onChange={this.analyze} /></p>
            </div>
        );
    }

}

export default PasswordStrength;

Let’s break down what’s happening starting with the constructor method. Because we plan to change the color of our background throughout the life-cycle of the component, we need to define a field within our state to accomplish that. This field is going to represent an actual CSS property that will be rendered as it changes.

Because we want our state variable to be changed within a function as logic is completed, we need to make sure that the function in question has the application context, hence why we are using the bind function.

Before we look at the analyze function, let’s look at the render function:

render() {
    return (
        <div style={{ backgroundColor: this.state.backgroundColor }}>
            <p><label for="password">Password: </label></p>
            <p><input type="text" name="password" onChange={this.analyze} /></p>
        </div>
    );
}

The parent HTML element has a style for background that will change as the state variable changes. The analyze function is called from a change event on the password input field.

So let’s take a look at some of the heavy lifting.

We know the regular expression logic for checking passwords won’t change dynamically. Let’s define these regular expressions as constants outside of the class, but within the src/components/passwordstrength.js file:

const strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
const mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");

I pulled these regular expressions from my previous tutorial.

So what do these regular expressions mean?

Let’s look at the following table which will illustrate a flow of events:

RegExDescription
^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

The above table is a breakdown of the regular expression for testing strong passwords. It can be modified to whatever you interpret to be a strong password.

The medium strength check is slightly different because of the use of the | operator which is an or event. Basically we’re saying a medium strength password satisfies two different characters while having an overall specific length.

To actually make the test happen, let’s jump back to the analyze function:

analyze(event) {
    if(strongRegex.test(event.target.value)) {
        this.setState({ backgroundColor: "#0F9D58" });
    } else if(mediumRegex.test(event.target.value)) {
        this.setState({ backgroundColor: "#F4B400" });
    } else {
        this.setState({ backgroundColor: "#DB4437" });
    }
}

First we check to see if the text from the input field is a strong password, otherwise we check to see if it is a medium password. If it is neither and it has been touched, then it is a poor password.

We can further improve this example through some CSS. Open the project’s src/components/passwordstrength.css and include the following:

.PasswordStrength {
    background-color: #4285F4;
    padding: 25px;
    color: #FFFFFF;
    font-weight: bold;
}

.PasswordStrength p {
    display: flex;
}

.PasswordStrength input {
    padding: 5px;
    flex-grow: 1;
    outline: none;
}

If you did everything correctly, you should have the same experience that I demonstrated in the animated image towards the top of this tutorial.

Conclusion

You just saw how to test password strength in a React application using simple JavaScript and regular expressions (RegEx). While the JavaScript can be used with any framework, like demonstrated in the AngularJS example, it is quite a powerful feature that you’re influencing your users with. You’re influencing them to build stronger passwords for your application which in turn should help prevent them from being compromised.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.