JAVASCRIPT
Validate Password Strength with Regex Lookaheads
Enforce strong password policies by using a single regular expression with lookaheads to validate minimum length and required character types.
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\|,.<>/?]).{8,}$/;
function isStrongPassword(password) {
return passwordRegex.test(password);
}
// Examples
console.log(isStrongPassword("P@sswOrd1")); // true
console.log(isStrongPassword("SecureP@ss2023")); // true
console.log(isStrongPassword("password")); // false (missing uppercase, number, special)
console.log(isStrongPassword("WeakP1")); // false (too short)
console.log(isStrongPassword("MyPass#1")); // true
How it works: This regex pattern effectively validates password strength by utilizing positive lookaheads (`(?=...)`). Each lookahead asserts the presence of a specific character type (lowercase, uppercase, digit, and a special character) anywhere in the string, without consuming the characters. The final `.{8,}` then ensures that the overall password meets a minimum length requirement of 8 characters. This technique provides comprehensive validation in a single, concise expression.