How to Validate Password Strength in Real-Time with JavaScript

Creating a strong password is essential for security, and showing users how strong their password is — while they type — improves both user experience and safety.

In this tutorial, you’ll learn how to check password strength in real-time using only HTML, CSS and JavaScript, ideal for beginners.


👁️ Preview


🧱 Step 1: Create the Basic HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Password Strength Checker</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>

  <h2>Create a Password</h2>
  <input type="password" id="password" placeholder="Enter your password" />
  <div id="strength-message">Password strength: <span id="strength">-</span></div>

  <script src="script.js"></script>
</body>
</html>

🎨 Step 2: Style the Strength Message with CSS

body {
  font-family: Arial, sans-serif;
  padding: 2rem;
}

input {
  padding: 10px;
  width: 100%;
  max-width: 300px;
  margin-bottom: 1rem;
  font-size: 1rem;
}

#strength-message {
  font-weight: bold;
}

#strength.weak {
  color: red;
}

#strength.medium {
  color: orange;
}

#strength.strong {
  color: green;
}

⚙️ Step 3: Add JavaScript to Check Password Strength

const passwordInput = document.getElementById('password');
const strengthText = document.getElementById('strength');

passwordInput.addEventListener('input', function () {
  const value = passwordInput.value;

  let strength = '';
  let className = '';

  if (value.length < 6) {
    strength = 'Too short';
    className = 'weak';
  } else if (value.match(/[a-z]/) && value.match(/[A-Z]/) && value.match(/[0-9]/) && value.length >= 8) {
    strength = 'Strong';
    className = 'strong';
  } else if ((value.match(/[a-zA-Z]/) && value.match(/[0-9]/)) || value.length >= 6) {
    strength = 'Medium';
    className = 'medium';
  } else {
    strength = 'Weak';
    className = 'weak';
  }

  strengthText.textContent = strength;
  strengthText.className = className;
});

✅ How It Works

  • We listen to input events to check the password as the user types.
  • The script evaluates:
    • Length of the password
    • Use of lowercase, uppercase, and numbers
  • It updates the message and color in real-time.

🧠 Tips for Strong Passwords

  • Use at least 8 characters
  • Mix uppercase and lowercase letters
  • Include numbers and symbols

You can improve the logic later by checking for symbols or using libraries like zxcvbn (for advanced strength scoring).


✅ Final Result

You now have a real-time password strength checker that:

  • Works with just HTML, CSS and JavaScript
  • Gives feedback instantly
  • Encourages users to choose stronger passwords

Leave a Comment