← Back to all snippets
JAVASCRIPT

Validating Strong Passwords with Regex

Learn to validate strong passwords in JavaScript using a single regular expression, ensuring minimum length, uppercase, lowercase, numbers, and special characters for enhanced security.

function isValidStrongPassword(password) {
  // At least 8 characters long
  // Contains at least one uppercase letter
  // Contains at least one lowercase letter
  // Contains at least one number
  // Contains at least one special character (!@#$%^&*()_+-=[]{};:'",.<>/?`~)
  const strongPasswordRegex = new RegExp(
    "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_+-=[]{};:'\",.<>/?`~])[A-Za-z0-9!@#$%^&*()_+-=[]{};:'\",.<>/?`~]{8,}$"
  );
  return strongPasswordRegex.test(password);
}

console.log(isValidStrongPassword("MyStrongPass123!")); // true
console.log(isValidStrongPassword("weakpass")); // false
console.log(isValidStrongPassword("Strong123")); // false (missing special char)
How it works: This JavaScript function `isValidStrongPassword` uses a single comprehensive regular expression to validate password strength. It employs positive lookaheads `(?=...)` to assert the presence of a lowercase letter, an uppercase letter, a digit, and a special character, all independently, without consuming characters. Finally, it ensures the entire string matches at least 8 allowed characters (`[A-Za-z0-9!@#$%^&*()_+-=[]{};:'",.<>/?`~]{8,}$`).

Need help integrating this into your project?

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

Hire DigitalCodeLabs