← Back to all snippets
JAVASCRIPT

Client-Side Password Strength Validation

Implement real-time client-side password strength validation in JavaScript using regular expressions for a better user experience and initial security feedback.

function validatePasswordStrength(password) {
  const minLength = 8;
  const hasUppercase = /[A-Z]/;
  const hasLowercase = /[a-z]/;
  const hasNumber = /[0-9]/;
  const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>/?]/;

  let score = 0;
  const feedback = [];

  if (password.length >= minLength) {
    score++;
  } else {
    feedback.push(`- Must be at least ${minLength} characters long.`);
  }

  if (hasUppercase.test(password)) {
    score++;
  } else {
    feedback.push('- Must include at least one uppercase letter.');
  }

  if (hasLowercase.test(password)) {
    score++;
  } else {
    feedback.push('- Must include at least one lowercase letter.');
  }

  if (hasNumber.test(password)) {
    score++;
  } else {
    feedback.push('- Must include at least one number.');
  }

  if (hasSpecialChar.test(password)) {
    score++;
  } else {
    feedback.push('- Must include at least one special character (!@#$%...).');
  }

  return {
    score: score,
    strength: score < 3 ? 'Weak' : (score < 5 ? 'Moderate' : 'Strong'),
    feedback: feedback
  };
}
How it works: This JavaScript snippet provides client-side password strength validation, offering immediate feedback to users as they type. It defines several regular expressions to check for minimum length, presence of uppercase letters, lowercase letters, numbers, and special characters. Based on how many criteria are met, it assigns a `score` and a textual `strength` (Weak, Moderate, Strong). While this enhances user experience, it's crucial to remember that client-side validation alone is insufficient for security; robust server-side password validation and hashing (e.g., using Bcrypt) are always required.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs