JAVASCRIPT
Validate Strong Passwords with Regex
Use this JavaScript regex pattern to validate strong passwords, ensuring they meet minimum length, include uppercase, lowercase, numbers, and special characters.
function validateStrongPassword(password) {
const strongPasswordRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$");
return strongPasswordRegex.test(password);
}
// Examples:
console.log(validateStrongPassword("MyStrongP@ss1")); // true
console.log(validateStrongPassword("weakpass")); // false (no uppercase, no number, no special char, too short)
console.log(validateStrongPassword("OnlyWords")); // false (no number, no special char)
How it works: This JavaScript snippet provides a regular expression to validate password strength. The regex `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$` uses positive lookaheads (`(?=...)`) to assert the presence of at least one lowercase letter, one uppercase letter, one digit, and one special character (from the set `@$!%*?&`). It then ensures the password contains only allowed characters (`[A-Za-z\d@$!%*?&]`) and is at least 8 characters long (`{8,}`). The `test()` method returns `true` if the password matches the pattern, `false` otherwise.