验证表单:如何一次性显示空白输入的错误消息而不是一个一个?

时间:2014-03-11 07:30:06

标签: javascript

我想验证我的表单,如果任何输入字段为空,则错误警告将显示在空白输入字段旁边。对于空白输入,必须同时显示错误消息,而不是逐个显示。怎么做?

以下是我的javascript代码:

    function doValidate()
    {
        var x=document.forms["form"]["fullname"].value;
        if (x==null || x=="")
            {
            document.getElementById('error1').innerHTML="Full name is required!";
            return false;
            }

        var y=document.forms["form"]["uid"].value;
        if (y==null || y=="")
            {
            document.getElementById('error2').innerHTML="Username is required!";
            return false;
            }

        var z=document.forms["form"]["pwd"].value;
        if (z==null || z=="")
            {
            document.getElementById('error3').innerHTML="Password is required!";
            return false;
            }

        var a=document.forms["form"]["pwd2"].value;
        if (a==null || a=="")
            {
            document.getElementById('error4').innerHTML="Please re-enter your password!";
            return false;
            }

        var pwd = document.getElementById("pwd").value;
        var pwd2 = document.getElementById("pwd2").value;
        if(pwd != pwd2){
            alert('Wrong confirm password!');
            return false;
        }

        var b=document.forms["form"]["role"].value;
        if (b==null || b=="Please select...")
            {
            document.getElementById('error5').innerHTML="Please select user role!";
            return false;
            }

    }

1 个答案:

答案 0 :(得分:3)

您应该使用var ok = true启动您的功能,并且在每个if - 块中,而不是return false,您应该设置ok = false。最后,返回ok

这可能是这样的:

function doValidate() {
    var ok = true;

    var form = document.forms.form;

    var fullname = form.fullname.value;
    if (fullname == null || fullname == "") {
        document.getElementById('error1').innerHTML = "Full name is required!";
        ok = false;
    }

    var uid = form.uid.value;
    if (uid == null || uid == "") {
        document.getElementById('error2').innerHTML = "Username is required!";
        ok = false;
    }

    var pwd = form.pwd.value;
    if (pwd == null || pwd == "") {
        document.getElementById('error3').innerHTML = "Password is required!";
        ok = false;
    }

    var pwd2 = form.pwd2.value;
    if (pwd2 == null || pwd2 == "") {
        document.getElementById('error4').innerHTML = "Please re-enter your password!";
        ok = false;
    } else if (pwd != pwd2) {
        document.getElementById('error4').innerHTML = "Wrong confirm password!";
        ok = false;
    }

    var role = form.role.value;
    if (role == null || role == "Please select...") {
        document.getElementById('error5').innerHTML = "Please select user role!";
        ok = false;
    }

    return ok;
}

(我冒昧地改为更一致的格式化风格,改进了一些变量名,简化了一些访问模式,并用其他内联错误消息替换了alert。)