JAVASCRIPT

Validate Password for Strong Requirements

Implement a JavaScript function with regular expressions to enforce strong password policies, requiring minimum length, uppercase, lowercase, numbers, and special characters.

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

  if (password.length < minLength) {
    return false;
  }
  if (!hasUppercase.test(password)) {
    return false;
  }
  if (!hasLowercase.test(password)) {
    return false;
  }
  if (!hasNumber.test(password)) {
    return false;
  }
  if (!hasSpecialChar.test(password)) {
    return false;
  }
  return true;
}

// Examples
console.log(isStrongPassword("MyPass123!")); // true
console.log(isStrongPassword("weakpass")); // false (no uppercase, no number, no special char)
console.log(isStrongPassword("NoNumber!")); // false (no number)
How it works: This `isStrongPassword` function checks a password against multiple criteria for strength using individual regular expressions. It verifies if the password meets a minimum length, and contains at least one uppercase letter, one lowercase letter, one digit, and one special character. Each `test()` call checks a specific regex pattern, returning `true` only if all conditions are met.

Need help integrating this into your project?

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

Hire DigitalCodeLabs