JAVASCRIPT

Enforcing Password Strength with Regex

Implement robust password strength validation in JavaScript using regex to ensure passwords include uppercase, lowercase, numbers, and special characters.

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

  if (password.length < minLength) {
    return "Password must be at least 8 characters long.";
  }
  if (!hasUpperCase) {
    return "Password must contain at least one uppercase letter.";
  }
  if (!hasLowerCase) {
    return "Password must contain at least one lowercase letter.";
  }
  if (!hasNumber) {
    return "Password must contain at least one number.";
  }
  if (!hasSpecialChar) {
    return "Password must contain at least one special character.";
  }
  return "Password is strong!";
};

console.log(validatePasswordStrength("Pass123!"));   // "Password is strong!"
console.log(validatePasswordStrength("weakpass"));  // "Password must contain at least one uppercase letter."
How it works: This JavaScript function `validatePasswordStrength` checks if a given password meets several strength criteria using individual regular expressions. It verifies minimum length, presence of uppercase letters, lowercase letters, numbers, and special characters. The function returns a descriptive message indicating which criteria are not met, or a success message if the password is strong.

Need help integrating this into your project?

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

Hire DigitalCodeLabs