JavaScript 使用函数和 if 语句进行表单验证

JavaScript Form Validation using function and if statement

看这段代码:

var UserName = document.getElementById("username");
var PassWord = document.getElementById("password");

function ValidateFormBeforePHP() {

    if (UserName.value == "" || UserName.value.length < 10) { alert("Please fill in username or characters to 10 or more"); }
    UserName.focus();
    UserName.style.border = "1px solid red");

    if (PassWord.value == "" || PassWord.value.length < 10) { alert("Please fill in password or characters to 10 or more"); }
    PassWord.focus();
    PassWord.style.border = "1px solid red");

    return false;

}

如果两个语句都为假,则不会 post / 登录。

应该是这样的:

function ValidateFormBeforePHP() {

    if (UserName.value == "" || UserName.value.length < 10) {
        alert("Please fill in username or characters to 10 or more");
        UserName.focus();
        UserName.style.border = "1px solid red";
        return false;
    }


    if (PassWord.value == "" || PassWord.value.length < 10) {
        alert("Please fill in password or characters to 10 or more");
        PassWord.focus();
        PassWord.style.border = "1px solid red";
        return false;
    }

    return true;

}