im trying to validate a password field with the following conditions, if the requirements are meet the password field should change its color to green if not should be red: One lowercase character One uppercase character One number One special character Eight characters minimum i tried with a regular expression but somehow it only makes it red even if i input a password with all the requirements. Any idea?
let passwordField = document.getElementById("password");
passwordField.addEventListener("focusout", () => {
let checkPass =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$/;
if (checkPass.test(password.value)) {
passwordField.style.backgroundColor = "green";
console.log("green");
} else {
passwordField.style.backgroundColor = "red";
console.log("red");
}
});
RegEx should be:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})
Where:
(?=.*[az])
(?=.*[AZ])
(?=.*[0-9])
(?=.*[!@#\\$%\\^&\\*])
(?=.{8,})
let passwordField = document.getElementById("password"); passwordField.addEventListener("focusout", () => { let checkPass = new RegExp("^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*])(?=.{8,})"); if (checkPass.test(password.value)) { passwordField.style.backgroundColor = "green"; console.log("green"); } else { passwordField.style.backgroundColor = "red"; console.log("red"); } });
<input id="password" />
And the result is:
Please check this, it is exact same you want
let passwordField = document.getElementById("password"); passwordField.addEventListener("focusout", () => { var decimal= /^(?=.*\\d)(?=.*[!@#$%^&*])(?=.*[az])(?=.*[AZ]).{8,}$/; if (passwordField.value.match(decimal)) { passwordField.style.backgroundColor = "green"; console.log("green"); } else { passwordField.style.backgroundColor = "red"; console.log("red"); } });
<!DOCTYPE html> <html lang="en"> <head> <title>Password</title> </head> <body> <h1>This is a password validation</h1> <input id="password" /> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.