JAVASCRIPT
Validate Strong Password Policy (Min 8 Chars, Mixed Case, Digit, Special)
Implement a strong password validation using a single JavaScript regex to enforce minimum length, uppercase, lowercase, numbers, and special characters.
function validateStrongPassword(password) {
// Minimum 8 characters, at least one uppercase letter, one lowercase letter,
// one number, and one special character (from @$!%*?&)
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
return passwordRegex.test(password);
}
// Example usage:
console.log(validateStrongPassword("MyP@ssw0rd!")); // true
console.log(validateStrongPassword("weakpass")); // false
console.log(validateStrongPassword("NoNumber!")); // false
console.log(validateStrongPassword("password")); // false
How it works: This function validates a password against a strong policy using a complex regular expression. The regex `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/` utilizes positive lookaheads (`(?=...)`) to ensure the presence of at least one lowercase letter, one uppercase letter, one digit, and one specified special character, independently of their position. Finally, it asserts the password is at least 8 characters long and only contains allowed characters.