You’ve probably seen many examples of password strength indicators around the web. They let users know the password they’re using is weak and indicate how the strength changes when it’s modified. In this tutorial we’ll be building a password strength indicator like the following:
Let’s start with the HTML creating a password input field and a password strength <div>
that we can style later on to give a visual representation of password strength:
<div id="password">
<label for="password-input">Password</label>
<input
id="password-input"
name="password-input"
type="password"
required
/>
<div id="password-strength"><span></span></div>
</div>
Code language: HTML, XML (xml)
To determine the password strength we’ll be using the zxcvbn JavaScript library which i’ve included via CDN. It’s also available as a standalone download and NPM package:
<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
Code language: HTML, XML (xml)
Now for the JavaScript, first let’s define variables for the password input and password strength:
const pwd = document.getElementById("password-input");
const pwdStrength = document.getElementById("password-strength");
Code language: JavaScript (javascript)
We’ll then use an event listener to check the password strength each time a character is added or removed from the password input field:
pwd.addEventListener("input", function () {
const pwdVal = pwd.value;
let result = zxcvbn(pwdVal);
pwdStrength.className += "strength-" + result.score;
});
Code language: JavaScript (javascript)
The score returned from zxcvbn()
is on a scale between 0 and 4. We then add this score as a class on the password strength <div>
so we can apply different CSS styles based on the score that’s returned.
That’s completes the JavaScript, now for the CSS starting with the password label and input field:
#password {
width: 250px;
}
#password label {
display: block;
}
#password-input {
width: 230px;
padding: 10px;
margin: 10px 0 5px 0;
}
Code language: CSS (css)
Now for the strength indicator, it’ll appear as a light grey strip until a user starts entering a password:
#password-strength {
height: 5px;
width: 100%;
display: block;
background-color: #ccc;
}
#password-strength span {
display: block;
height: 5px;
border-radius: 2px;
transition: all 500ms ease;
}
Code language: CSS (css)
All that’s left to do is set the color and width based on the strength score:
.strength-0 span {
background-color: red;
width: 5%;
}
.strength-1 span {
background-color: orangered;
width: 25%;
}
.strength-2 span {
background-color: orange;
width: 50%;
}
.strength-3 span {
background-color: yellowgreen;
width: 75%;
}
.strength-4 span {
background-color: green;
width: 100%;
}
Code language: CSS (css)