JAVASCRIPT

Enforcing Password Strength with Regex for Security

Implement strong password policies in JavaScript with a single regular expression to check for minimum length, special characters, numbers, and mixed case.

function isStrongPassword(password) {
  // Must contain at least one uppercase letter, one lowercase letter, one number, and one special character.
  // Must be at least 8 characters long.
  const passwordRegex = new RegExp(
    /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':\",.<>/?`~])(?=.{8,})/
  );
  return passwordRegex.test(password);
}

// Examples:
console.log(isStrongPassword("StrongP@ss1"));  // true
console.log(isStrongPassword("weakpassword"));  // false (no uppercase, no number, no special char)
console.log(isStrongPassword("P@ss1"));       // false (too short)
console.log(isStrongPassword("Passw0rd!"));    // true
How it works: The `isStrongPassword` function validates a password against several common strength criteria using lookaheads in a single regular expression. `(?=.*[a-z])` ensures at least one lowercase letter, `(?=.*[A-Z])` for uppercase, `(?=.*\d)` for a digit, and `(?=.*[!@#$%^&*...])` for a special character. Finally, `(?=.{8,})` enforces a minimum length of 8 characters. This provides a robust client-side check for password complexity.

Need help integrating this into your project?

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

Hire DigitalCodeLabs