JAVASCRIPT
Validate Password Strength with Multiple Criteria
A JavaScript regex pattern for robust password validation. Ensures passwords meet criteria like minimum length, uppercase, lowercase, numbers, and special characters.
function validatePassword(password) {
const minLength = 8;
const hasUppercase = /[A-Z]/;
const hasLowercase = /[a-z]/;
const hasNumber = /[0-9]/;
const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
if (password.length < minLength) {
return "Password must be at least " + minLength + " characters long.";
}
if (!hasUppercase.test(password)) {
return "Password must contain at least one uppercase letter.";
}
if (!hasLowercase.test(password)) {
return "Password must contain at least one lowercase letter.";
}
if (!hasNumber.test(password)) {
return "Password must contain at least one number.";
}
if (!hasSpecialChar.test(password)) {
return "Password must contain at least one special character.";
}
return "Password is strong.";
}
console.log(validatePassword("SecureP@ss1")); // Password is strong.
console.log(validatePassword("weakpass")); // Password must contain at least one uppercase letter.
console.log(validatePassword("Strongpass1")); // Password must contain at least one special character.
console.log(validatePassword("P@ssword")); // Password must contain at least one number.
How it works: This JavaScript function uses multiple regular expressions to enforce strong password policies. It checks if a given password meets criteria such as a minimum length, and the presence of at least one uppercase letter, one lowercase letter, one number, and one special character. Each `test()` call verifies a specific regex pattern, providing clear feedback if a criterion is not met.