与我编写的一些JavaScript相关的一些查询没有表现出我认为它应该如何。它是一个密码验证表单,有2个输入字段,允许用户输入密码,然后重新输入密码以查看是否有匹配
这是功能。
function passwordValidation(){
var uname = document.getElementById("pword1").value;
var pword = document.getElementById("cPassword").value;
var matchCol = "#009900";
var noMatchCol = "#CC0000";
var noBg = "#FFFFFF";
var passReq = new RegExp ("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\"\.\[\]_£|`¬':;~{}<>()#?!@$%^&*-]).{8,20}$");
if (uname.length < 1 || pword.length < 1){
cPassword.style.backgroundColor = noBg;
match = "";
}
if(passReq.test(pword1)){
DIMR = "Does Meet Requirements";
}else {
DIMR = "Does Not Meet Requirements";
}
if (uname == pword){
match = "Match!";
cPassword.style.backgroundColor = matchCol;
} else{
match = "No Match!";
cPassword.style.backgroundColor = noMatchCol;
}
document.getElementById("combination").innerHTML = match;
document.getElementById("reqMeeting").innerHTML = DIMR;
}
首先,为什么忽略第一个if语句?当我在浏览器中加载代码并运行它时。只要在第一个输入框中键入值,第二个输入框就会变为红色。即使if语句明确表示如果输入OR输入b为空白,也不要这样做。
其次,.test
部分无法正常工作。也许我的代码是错的,但对我来说,如果正则表达式passReq
与pword1
值匹配,则打印出"does/does not meet requirements"
。我还将其更改为变量名passReq.test(uname)
,但仍未发生任何事情。
答案 0 :(得分:1)
那是因为那是一个单独的if
条件。因此,无论结果如何,它都将继续下一个条件。我想您必须使用else
部分与第一个if
条件来获得您想要的预期结果。
function passwordValidation() {
var uname = document.getElementById("pword1").value;
var pword = document.getElementById("cPassword").value;
var matchCol = "#009900";
var noMatchCol = "#CC0000";
var noBg = "#FFFFFF";
var passReq = new RegExp("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\"\.\[\]_£|`¬':;~{}<>()#?!@$%^&*-]).{8,20}$");
if (uname.length < 1 || pword.length < 1) {
cPassword.style.backgroundColor = noBg;
match = "";
} else { // this should solve the problem
if (passReq.test(pword)) {
DIMR = "Does Meet Requirements";
} else {
DIMR = "Does Not Meet Requirements";
}
if (uname == pword) {
match = "Match!";
cPassword.style.backgroundColor = matchCol;
} else {
match = "No Match!";
cPassword.style.backgroundColor = noMatchCol;
}
document.getElementById("combination").innerHTML = match;
document.getElementById("reqMeeting").innerHTML = DIMR;
}
}