Customer Data PlatformsEmail Marketing & Automation

Check Password Strength with JavaScript or jQuery and Regular Expressions (With Server-Side Example, Too!)

In an era of sophisticated credential stuffing and brute-force attacks, the minimum 8 characters rule is no longer enough. To truly protect user data, we need password fields that enforce not just length but also complexity, randomness, and resistance to common patterns.

I was doing some research on finding a good example of a Password Strength checker that uses JavaScript and Regular Expressions (Regex). In the application at my work, we do a postback to verify password strength, which is quite inconvenient for our users.

What is Regex?

A regular expression is a sequence of characters that define a search pattern. Usually, such patterns are used by string searching algorithms for find or find and replace operations on strings, or for input validation. 

This article is definitely not meant to teach you regular expressions. Just know that the ability to use Regular Expressions will absolutely simplify your development as you search for patterns in text. It’s also important to note that most development languages have optimized regular expression support, so rather than parsing and searching strings step-by-step, Regex is typically much faster on both the server and client sides.

I searched the web quite a bit before I found 1 Regular Expressions that look for combinations of length, characters, and symbols. However, the code was a little excessive for my taste and tailored for .NET. So I simplified the code and put it in JavaScript. This validates password strength in real-time in the client’s browser before posting it back… and provides feedback to the user on the password’s strength.

A great password UI should do three things:

  1. Educate: Show the user exactly what is required.
  2. Validate: Provide real-time feedback on password strength.
  3. Assist: Offer a “Generate” button for users who want a bulletproof password without the mental effort.

Type A Password

With each keystroke, the password is tested against the regular expression, and feedback is provided to the user in a span beneath the field.

[passwordstrength class=”app-container”]

JavaScript Password Strength Function

To move beyond basic checks, our script evaluates a password based on eight distinct security dimensions:

  • Length: A minimum of 12 characters to increase the time needed for brute-forcing.
  • Character Diversity: Requires a mix of lowercase, uppercase, numbers, and special symbols ($!@#$…).
  • Pattern Recognition: It detects and rejects common keyboard sequences (like qwerty or 12345) and repeated characters (like aaa).
  • Blacklisting: It checks against a dictionary of commonly used passwords (e.g., “password”, “123456”) that are the first targets in any dictionary attack.
  • Entropy Calculation: It measures the mathematical unpredictability of the string.

Implementation: The Core Logic

Below are the two vital functions: one to evaluate the input and another to generate a compliant, high-entropy password using the browser’s native Cryptography API for true randomness.

1. The Strength Evaluator

This function returns a score and a breakdown of which security checks passed.

function evaluatePassword(pw) {
    const checks = {
        length:        pw.length >= 12,
        lowercase:     /[a-z]/.test(pw),
        uppercase:     /[A-Z]/.test(pw),
        digit:         /[0-9]/.test(pw),
        special:       /[^a-zA-Z0-9]/.test(pw),
        'no-repeat':   !/(.)\1{2,}/.test(pw), 
        'no-sequence': !hasSequence(pw),      
        'no-common':   !isCommon(pw)          
    };

    let passed = Object.values(checks).filter(Boolean).length;
    
    let level = 0;
    if (pw.length > 0) {
        if (passed <= 2) level = 1;      
        else if (passed <= 4) level = 2; 
        else if (passed <= 6) level = 3; 
        else if (passed < 8) level = 4;  
        else level = 5;                 
    }

    return { checks, level };
}

2. The Strong Password Generator

We don’t just pick random letters; we ensure the result immediately satisfies all our criteria.

function generateStrongPassword() {
    const sets = [
        'abcdefghijklmnopqrstuvwxyz',
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        '0123456789',
        '!@#$%^&*()-_=+[]{}|;:,.<>?'
    ];
    let pw = "";
    
    sets.forEach(set => {
        const array = new Uint32Array(1);
        window.crypto.getRandomValues(array);
        pw += set[array[0] % set.length];
    });

    const allChars = sets.join('');
    for (let i = 4; i < 16; i++) {
        const array = new Uint32Array(1);
        window.crypto.getRandomValues(array);
        pw += allChars[array[0] % allChars.length];
    }

    return pw.split('').sort(() => 0.5 - Math.random()).join('');
}

Displaying the Form

To implement this on your site, use a clean HTML structure that includes a container for the strength meter and a list of requirements.

<div class="password-wrapper">
    <label for="mtz-pw-input">Create Password</label>
    <div class="input-group">
        <input type="password" id="mtz-pw-input" placeholder="Enter password...">
        <button id="mtz-pw-toggle">Show</button>
        <button id="mtz-pw-generate">Generate</button>
    </div>

    <div class="mtz-pw-meter-container">
        <div id="mtz-pw-meter-fill" style="height: 10px; transition: width 0.3s;"></div>
    </div>
    <small id="mtz-pw-label"></small>

    <ul id="mtz-pw-requirements">
        <li data-req="length">At least 12 characters</li>
        <li data-req="lowercase">One lowercase letter</li>
        <li data-req="uppercase">One uppercase letter</li>
        <li data-req="digit">One number</li>
        <li data-req="special">One special character</li>
    </ul>
</div>

Never Trust the Client: Server-Side Validation

While the JavaScript UI provides a great user experience, frontend checks are easily bypassed. A malicious user can disable JavaScript or send a manual POST request to your server with a weak password.

You must always mirror your validation logic on the backend. Here is how you can perform the same high-standard check in PHP:

function is_password_strong($password) {
    // 1. Length check
    if (strlen($password) < 12) return false;

    // 2. Character diversity
    if (!preg_match('/[a-z]/', $password)) return false;
    if (!preg_match('/[A-Z]/', $password)) return false;
    if (!preg_match('/[0-9]/', $password)) return false;
    if (!preg_match('/[^a-zA-Z0-9]/', $password)) return false;

    // 3. No 3+ repeated characters (e.g., aaa)
    if (preg_match('/(.)\1{2,}/', $password)) return false;

    // 4. Check common passwords (abbreviated list)
    $common = ['password', '123456', 'qwerty', 'welcome'];
    if (in_array(strtolower($password), $common)) return false;

    return true;
}

// Usage in your registration script
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!is_password_strong($_POST['password'])) {
        die("Error: Password does not meet security requirements.");
    }
    // Proceed to hash and save password...
}

By combining real-time UI feedback with a strict PHP fallback, you ensure that your application remains secure even if the user’s browser is compromised or manipulated.

And if you’re just looking for a great password generator, I’ve built a nice little online tool for that.

Password Generator

Related Articles