In this article we're going to create a JavaScript password strength meter using the zxcvbn library.

zxcvbn is a powerful library that checks the entropy and strength of a given password. It's very simple to use: we pass the password to the constructor and we get a result object containing various information.

The information that we'll use here is the score property that reports a score from 0 to 4 indicating the five levels of strength of a password.

First, we need a form and a basic markup structure for our meter:

<form id="test-form" action="" method="post" novalidate>
    <div class="form-group">
        <label for="password">Choose a password</label>
        <input type="text" name="password" id="password" class="form-control">
        <div class="password-meter-wrap">
            <div class="password-meter-bar"></div>

Then we can create five CSS classes with an increasing width and a different background color to be applied to the inner bar dynamically.

.password-meter-wrap {
    margin-top: 5px;
    height: 16px;
    background-color: #ddd;

.password-meter-bar {
    width: 0;
    height: 100%;
    transition: width 400ms ease-in;

.password-meter-bar.level0 {
    width: 20%;
    background-color: #d00;
.password-meter-bar.level1 {
    width: 40%;
    background-color: #f50;
.password-meter-bar.level2 {
    width: 60%;
    background-color: #ff0;
.password-meter-bar.level3 {
    width: 80%;
    background-color: rgb(161, 168, 65);

.password-meter-bar.level4 {
    width: 100%;
    background-color: #393;

Five levels, five classes, five different widths that range from 0 to 100% with a singular step equal to 20% because 100 / 5 = 20.

Now we can write the JavaScript logic:

'use strict';

class PasswordMeter {
    constructor(selector) {
        this.wrappers = document.querySelectorAll(selector);
        if(this.wrappers.length > 0) {
    init(wrappers) {
        wrappers.forEach(wrapper => {
            let bar = wrapper.querySelector('.password-meter-bar');
            let input = wrapper.previousElementSibling;

            input.addEventListener('keyup', () => {
                let value = input.value;
                bar.classList.remove('level0', 'level1', 'level2', 'level3', 'level4');
                let result = zxcvbn(value);
                let cls = `level${result.score}`;
            }, false);

document.addEventListener('DOMContentLoaded', () => {
    const passwordMeter = new PasswordMeter('.password-meter-wrap');
}, false);

We bind a keyup event on the password field where we check the password strength using the zxcvbn library's constructor. We get our result and we use the integere value to dynamically change the CSS classes of the inner bar. As you can see, this logic is really straightforward.


JavaScript: password strength meter with zxcvbn