Black Friday: Enjoy a 35% discount on the bundles. Apply the code BLACKFRIDAY35 at checkout! Limited offer.

← Back to all tutorials

How to create a password strength meter with Tailwind CSS and JavaScript

js-password-strength-meter
Published and written on Sep 04 2024 by Michael Andreuzza

Let’s recreate the same password strength meter using JavaScript instead of Alpine JS.

A quick refresh: What are password strength meters?

Password strength meters are a great way to ensure that users are creating strong passwords. We all know that passwords are one of the most commonly used online security measures, and it’s essential to create strong passwords to protect your accounts and personal information.

Use cases

Password strength meters are a valuable tool in enhancing security by encouraging users to create strong and secure passwords. Below are some key use cases:

  1. Account Creation:

    • Scenario: When users sign up for a new account on a website or application.
    • Purpose: To ensure that new users set strong passwords during registration, reducing the risk of weak passwords that could be easily compromised.
  2. Password Updates:

    • Scenario: When existing users need to update or reset their passwords.
    • Purpose: To guide users in choosing stronger passwords when they change their existing ones, especially after a security incident or a routine password update.
  3. Corporate Security Policies:

    • Scenario: In enterprise environments where employees are required to set up or update their login credentials.
    • Purpose: To enforce corporate password policies that mandate a certain level of password complexity, ensuring compliance with internal security standards.
  4. E-Commerce Platforms:

    • Scenario: When users create accounts or update passwords on e-commerce websites.
    • Purpose: To protect sensitive customer information, such as payment details, by encouraging the creation of strong passwords.
  5. Financial Applications:

    • Scenario: When users create or update passwords for online banking, investment platforms, or other financial services.
    • Purpose: To enhance the security of financial accounts by ensuring that users create highly secure passwords, reducing the risk of unauthorized access.
  6. Social Media Platforms:

    • Scenario: When users sign up or update their passwords on social media accounts.
    • Purpose: To help users protect their social media profiles from unauthorized access, which can lead to identity theft or privacy breaches.
  7. Health and Medical Records:

    • Scenario: When users set up accounts on healthcare platforms that store sensitive personal health information.
    • Purpose: To ensure that passwords protecting health records meet strong security standards, safeguarding highly sensitive data.
  8. Education Portals:

    • Scenario: For students and educators when accessing online learning platforms.
    • Purpose: To ensure secure access to educational resources and protect student information by encouraging strong passwords.
  9. Government Services:

Let’s write the markup

The input

Attributes

  • id="password": Assigns a unique ID to the input.
  • type="password": Sets the input type to password.
<input id="password" type="password" />

The button to toggle the password visibility

The button is used to toggle the visibility of the password input based on the showPassword variable.

  • id="toggle-password": Assigns a unique ID to the button.
  • type="button": Sets the button type to button.

The icons

The button contains two span elements, one for the password visibility icon and one for the password strength icon.

  • id="show-eye": Assigns a unique ID to the password visibility icon.
  • id="hide-eye": Assigns a unique ID to the password strength icon. This icons has a class of text-blue-500 to set the color to blue and it will be initially hidden.
<button id="toggle-password" type="button">
  <span id="show-eye">
    <!-- SVG goes here -->
  </span>
  <span id="hide-eye" class="text-blue-500" style="display: none;">
    <!-- SVG goes here -->
  </span>
</button>

The meter itself

The meter is a progress bar that displays the strength of the password based on the number of characters, uppercase letters, lowercase letters, and special characters. The progress bar

  • id="strength-bar": Assigns a unique ID to the meter. This will allow to target the progress bar and apply diferent colors based on the strength of the password. The text
  • id="strength-text": Assigns a unique ID to the text. This text will display the strength of the password and it will be reflected with colors based on the strength of the password.
<div id="strength-bar" style="width: 0;"></div>

Note: Irrelevant classes and attributes are removed for brevity and you can get the full code on the GitHub repository.

  <div>
  <!-- Password Input -->
  <div>
    <label for="password" class="sr-only">Password</label>
    <div class="relative">
      <input id="password" type="password" />
      <button id="toggle-password" type="button">
        <span id="show-eye">
          <!-- SVG goes here -->
        </span>
        <span id="hide-eye" class="text-blue-500" style="display: none;">
          <!-- SVG goes here -->
        </span>
      </button>
    </div>
  </div>
  <!-- Password Strength Meter -->
  <div>
    <div id="strength-bar" style="width: 0;"></div>
  </div>
  <!-- Password Strength Text -->
  <p id="strength-text"> Password strength: <span id="strength-label">weak</span>
  </p>
</div>

The script

The addEventListener

We’ll add the addEventListener function to the document object to listen for the DOMContentLoaded event.

  • const passwordInput = document.getElementById("password");: This line of code selects the password input element with the ID password.
  • const togglePasswordButton = document.getElementById("toggle-password");: This line of code selects the button element with the ID toggle-password.
  • const showEye = document.getElementById("show-eye");: This line of code selects the password visibility icon element with the ID show-eye.
  • const hideEye = document.getElementById("hide-eye");: This line of code selects the password strength icon element with the ID hide-eye.
  • const strengthBar = document.getElementById("strength-bar");: This line of code selects the progress bar element with the ID strength-bar.
  • const strengthLabel = document.getElementById("strength-label");: This line of code selects the text element with the ID strength-label.
  • const strengthText = document.getElementById("strength-text");: This line of code selects the text element with the ID strength-text.
  • let showPassword = false;: This line of code declares a variable showPassword and initializes it to false.
const passwordInput = document.getElementById("password");
     const togglePasswordButton = document.getElementById("toggle-password");
     const showEye = document.getElementById("show-eye");
     const hideEye = document.getElementById("hide-eye");
     const strengthBar = document.getElementById("strength-bar");
     const strengthLabel = document.getElementById("strength-label");
     const strengthText = document.getElementById("strength-text");
     let showPassword = false;

The checkStrength function

The checkStrength function will check the strength of the password based on the number of characters, uppercase letters, lowercase letters, and special characters.

  • let strength = "weak";: This line of code declares a variable strength and initializes it to weak.
  • let width = "25%";: This line of code declares a variable width and initializes it to 25%.
  • let color = "red";: This line of code declares a variable color and initializes it to red.
  • const hasLowerCase = /[a-z]/.test(password);: This line of code declares a regular expression hasLowerCase that checks if the password contains lowercase letters.
  • const hasUpperCase = /[A-Z]/.test(password);: This line of code declares a regular expression hasUpperCase that checks if the password contains uppercase letters.
  • const hasNumber = /\d/.test(password);: This line of code declares a regular expression hasNumber that checks if the password contains numbers.
  • const hasSpecialChar = /[!@#$%^&*(),.?':{}|<>]/.test(password);: This line of code declares a regular expression hasSpecialChar that checks if the password contains special characters.
  • const passedChecks = [hasLowerCase, hasUpperCase, hasNumber, hasSpecialChar].filter(Boolean).length;: This line of code declares a variable passedChecks that filters the regular expressions and counts the number of passed checks.
  • if (password.length >= 8): This line of code checks if the password length is greater than or equal to 8.
  • if (passedChecks === 4 || password.length >= 12): This line of code checks if the number of passed checks is 4 or if the password length is greater than or equal to 12.
  • strength = "very strong";: This line of code sets the strength variable to very strong if the password length is greater than or equal to 12 and the number of passed checks is 4.
  • else if (passedChecks >= 3): This line of code checks if the number of passed checks is greater than or equal to 3.
  • strength = "strong";: This line of code sets the strength variable to strong if the number of passed checks is greater than or equal to 3.
  • else if (passedChecks >= 2): This line of code checks if the number of passed checks is greater than or equal to 2.
  • strength = "medium";: This line of code sets the strength variable to medium if the number of passed checks is greater than or equal to 2.
  • strengthBar.style.width = width;: This line of code sets the width of the progress bar to the width variable.
  • strengthBar.style.backgroundColor = color;: This line of code sets the background color of the progress bar to the color variable.
  • strengthLabel.textContent = strength;: This line of code sets the text content of the text element to the strength variable.
  • strengthText.style.color = color;: This line of code sets the color of the text element to the color variable.
function checkStrength(password) {
    let strength = "weak";
    let width = "25%";
    let color = "red";
    const hasLowerCase = /[a-z]/.test(password);
    const hasUpperCase = /[A-Z]/.test(password);
    const hasNumber = /\d/.test(password);
    const hasSpecialChar = /[!@#$%^&*(),.?':{}|<>]/.test(password);
    const passedChecks = [
        hasLowerCase,
        hasUpperCase,
        hasNumber,
        hasSpecialChar,
    ].filter(Boolean).length;
    if (password.length >= 8) {
        if (passedChecks === 4 || password.length >= 12) {
            strength = "very strong";
            width = "100%";
            color = "#3e88f7";
        } else if (passedChecks >= 3) {
            strength = "strong";
            width = "75%";
            color = "#4caf50";
        } else if (passedChecks >= 2) {
            strength = "medium";
            width = "50%";
            color = "orange";
        }
    }
    strengthBar.style.width = width;
    strengthBar.style.backgroundColor = color;
    strengthLabel.textContent = strength;
    strengthText.style.color = color;
}

The inputs listener

The input event listener will call the checkStrength function when the password input value changes.

  • passwordInput.addEventListener("input", (event) => {: This line of code adds an event listener to the password input element.
  • checkStrength(event.target.value);: This line of code calls the checkStrength function with the value of the password input.
passwordInput.addEventListener("input", (event) => {
    checkStrength(event.target.value);
});

The button listener

The button listener will toggle the visibility of the password input and change the icon based on the showPassword variable.

  • togglePasswordButton.addEventListener("click", () => {: This line of code adds an event listener to the button element.
  • showPassword = !showPassword;: This line of code toggles the showPassword variable.
  • passwordInput.type = showPassword ? "text" : "password";: This line of code sets the type of the password input based on the value of the showPassword variable.
  • showEye.style.display = showPassword ? "none" : "inline";: This line of code sets the display of the password visibility icon based on the value of the showPassword variable.
togglePasswordButton.addEventListener("click", () => {
    showPassword = !showPassword;
    passwordInput.type = showPassword ? "text" : "password";
    showEye.style.display = showPassword ? "none" : "inline";
    hideEye.style.display = showPassword ? "inline" : "none";
});

The complete script

 document.addEventListener("DOMContentLoaded", () => {
     const passwordInput = document.getElementById("password");
     const togglePasswordButton = document.getElementById("toggle-password");
     const showEye = document.getElementById("show-eye");
     const hideEye = document.getElementById("hide-eye");
     const strengthBar = document.getElementById("strength-bar");
     const strengthLabel = document.getElementById("strength-label");
     const strengthText = document.getElementById("strength-text");
     let showPassword = false;

     function checkStrength(password) {
         let strength = "weak";
         let width = "25%";
         let color = "red";
         const hasLowerCase = /[a-z]/.test(password);
         const hasUpperCase = /[A-Z]/.test(password);
         const hasNumber = /\d/.test(password);
         const hasSpecialChar = /[!@#$%^&*(),.?':{}|<>]/.test(password);
         const passedChecks = [
             hasLowerCase,
             hasUpperCase,
             hasNumber,
             hasSpecialChar,
         ].filter(Boolean).length;
         if (password.length >= 8) {
             if (passedChecks === 4 || password.length >= 12) {
                 strength = "very strong";
                 width = "100%";
                 color = "#3e88f7";
             } else if (passedChecks >= 3) {
                 strength = "strong";
                 width = "75%";
                 color = "#4caf50";
             } else if (passedChecks >= 2) {
                 strength = "medium";
                 width = "50%";
                 color = "orange";
             }
         }
         strengthBar.style.width = width;
         strengthBar.style.backgroundColor = color;
         strengthLabel.textContent = strength;
         strengthText.style.color = color;
     }
     passwordInput.addEventListener("input", (event) => {
         checkStrength(event.target.value);
     });
     togglePasswordButton.addEventListener("click", () => {
         showPassword = !showPassword;
         passwordInput.type = showPassword ? "text" : "password";
         showEye.style.display = showPassword ? "none" : "inline";
         hideEye.style.display = showPassword ? "inline" : "none";
     });
 });

Conclusion

In this tutorial, we learned how to create a password strength meter using JavaScript and Tailwind CSS, and how to use JavaScript to check the strength of a password based on the number of characters, uppercase letters, lowercase letters, and special characters.

I hope you found this tutorial helpful and have a great day!

/Michael Andreuzza

Did you like this tutorial? Please share it with your friends!

Own all themes forever for $199.

Includes new themes, updates, unlimited projects, and lifetime support. — No subscription required!