获取JavaScript以执行多个if语句

时间:2014-12-01 11:42:44

标签: javascript regex if-statement

如何使用以下JavaScript代码执行多个if语句,而不管上面的if语句是true还是false。

这是代码

var uname = document.getElementById("pword1").value;
    var pword = document.getElementById("cPassword").value;
    var passReq = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\"\.\[\]_£|`¬':;~{}<>()#?!@$%^&*-]).{8,20}$";

    var matchCol = "#009900";
    var noMatchCol = "#CC0000";
    var noBg = "#FFFFFF";


    if (uname.length < 1 || pword.length < 1){
        cPassword.style.backgroundColor = noBg;
        match = "";
    }else if(passReq.test(uname)){
        DIMR = "Does Meet Requirements";
    }else if(!passReq.test(uname)){
        DIMR = "Does Not Meet Requirements";
    }else if (pword1.value == cPassword.value){
        match = "Match!";
        cPassword.style.backgroundColor = matchCol;
    } else if  (pword1.value != cPassword.value){
        match = "No Match!";
        cPassword.style.backgroundColor = noMatchCol;
    }
    document.getElementById("combination").innerHTML = match;
    document.getElementById("reqMeeting").innerHTML = DIMR;
}

我有2个输入框。 &#34;密码&#34;和&#34;确认密码&#34;。我想要各种各样的事情发生,包括:如果没有输入,则不返回任何消息,如果密码不匹配则确认密码变为红色,如果匹配变为绿色,如果该值不符合正则表达式则发送屏幕上的另一条消息说&#34;不符合要求,如果它匹配表达式,则向屏幕发送不同的消息说&#34;确实符合要求&#34;。

2 个答案:

答案 0 :(得分:0)

您可能希望它更像:

var uname = document.getElementById("pword1").value;
    var pword = document.getElementById("cPassword").value;
    var passReq = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\"\.\[\]_£|`¬':;~{}<>()#?!@$%^&*-]).{8,20}$";
    var pwReqExp = new RegExp(passReq);

    var matchCol = "#009900";
    var noMatchCol = "#CC0000";
    var noBg = "#FFFFFF";


    if (uname.length < 1 || pword.length < 1){
        cPassword.style.backgroundColor = noBg;
        match = "";
    }

    if(pwReqExp.test(uname)){
        DIMR = "Does Meet Requirements";
    }else {
        DIMR = "Does Not Meet Requirements";
    }

    if (pword1.value == cPassword.value){
        match = "Match!";
        cPassword.style.backgroundColor = matchCol;
    } else {
        match = "No Match!";
        cPassword.style.backgroundColor = noMatchCol;
    }
    document.getElementById("combination").innerHTML = match;
    document.getElementById("reqMeeting").innerHTML = DIMR;
} 

更新: 添加了新的RegExp

var pwReqExp = new RegExp(passReq);
// ...
pwReqExp.test(uname)
// ...

答案 1 :(得分:0)

Javascript,就像java评估if语句和&#34;链接&#34;它们是前一个,所以你应该结束if并使用这个语法:

if (expression) {
//code goes here
}
else {}

if (other expression) {
//more code
} else {}

if (yet another expression) {
//even more code
} else {}