[英]Javascript password validation with regular expression
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.我尝试使用以下条件验证密码字段,如果满足要求,密码字段应将其颜色更改为绿色,否则应为红色: 一个小写字符 一个大写字符 一个数字 一个特殊字符 最少 8 个字符我尝试过正则表达式,但不知何故,即使我输入了具有所有要求的密码,它也只会使它变红。 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])
(?=.*[AZ])
(?=.*[AZ])
(?=.*[0-9])
(?=.*[0-9])
(?=.*[!@#\\$%\\^&\\*])
(?=.*[!@#\\$%\\^&\\*])
(?=.{8,})
(?=.{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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.