← Back to all snippets
JAVASCRIPT

Enforce Password Strength with Regex

Create a JavaScript function using regex to enforce strong password policies, requiring uppercase, lowercase, numbers, and special characters.

function isStrongPassword(password) {
  // Minimum 8 characters, at least one uppercase, one lowercase, one number, one special character
  const strongPasswordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+{}\[\]:;<>,.?~\\/-]).{8,}$/;
  return strongPasswordRegex.test(password);
}

// Examples:
// console.log(isStrongPassword("Pass123!")); // true
// console.log(isStrongPassword("password")); // false (no uppercase, no number, no special)
// console.log(isStrongPassword("P@ssword1")); // true
// console.log(isStrongPassword("Short1!")); // false (less than 8 chars)
How it works: This snippet introduces `isStrongPassword`, a JavaScript function that checks if a password meets specific strength criteria using a regular expression. The pattern `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+{}\[\]:;<>,.?~\\/-]).{8,}$` uses positive lookaheads to ensure the password contains at least one lowercase letter, one uppercase letter, one digit, and one special character, all while being a minimum of 8 characters long. This is crucial for enhancing user account security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs