JAVASCRIPT

Regex for Strong Password Validation

Create a JavaScript function to validate password strength using regex, ensuring it contains uppercase, lowercase, numbers, symbols, and meets a minimum length.

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

// Usage examples:
// console.log(isStrongPassword("StrongP@ss1")); // true
// console.log(isStrongPassword("weakpass")); // false (no uppercase, number, symbol)
// console.log(isStrongPassword("P@ss1")); // false (too short)
How it works: The `isStrongPassword` function validates password strength using a single regular expression with multiple positive lookaheads. It checks for a minimum length of 8 characters and ensures the password contains at least one lowercase letter (`(?=.*[a-z])`), one uppercase letter (`(?=.*[A-Z])`), one digit (`(?=.*\\d)`), and one special character (`(?=.*[!@#$%^&*...])`). This comprehensive pattern helps enforce robust password policies. Backslashes within the regex literal (e.g., `\\d`, `\\[`, `\\]`, `\"`) are correctly escaped for JSON string representation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs