[英]Javascript password validation with regular expression
我尝试使用以下条件验证密码字段,如果满足要求,密码字段应将其颜色更改为绿色,否则应为红色: 一个小写字符 一个大写字符 一个数字 一个特殊字符 最少 8 个字符我尝试过正则表达式,但不知何故,即使我输入了具有所有要求的密码,它也只会使它变红。 任何的想法?
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");
}
});
正则表达式应该是:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})
在哪里:
(?=.*[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" />
结果是:
请检查这个,它和你想要的完全一样
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.