javascript验证表单检查 - 回显表单中的错误?

时间:2014-03-31 11:27:02

标签: javascript validation

我目前有一个javascript代码验证我的表单,并在字段未完成时显示错误。我也想知道如何回应表格中的错误,例如,如果' fname'没有填写然后这说“你没有填写fname'或者如果' fname'和fcompany'没有填写这个说法

You did not fill in fname 
you did not fill in fcompany 

继承人我的HTML:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Company Name: <input type="text" name="fname">
Company Registration Number: <input type="text" name="fcompany">

继承人我的javascript:

<script>
function validateForm()
 {
 var x=document.forms["myForm"]["cname"].value;
 if (x==null || x=="")
   {
document.body.scrollTop = document.documentElement.scrollTop = 0;
   document.getElementById("alertBox").style.display='block';
   return false;
   }
 }
</script>

1 个答案:

答案 0 :(得分:1)

让你的验证函数构建一个错误数组,然后让另一个函数获取错误数组并构建HTML:

http://jsfiddle.net/J9LJj/

function displayErrors(errors){
    var container = document.getElementById("alertBox");
    var html = "<ul>";

    for(var i=0; i<errors.length; i++){
        html += "<li>" + errors[i] + "</li>";
    }
    html += "</ul>";

    container.innerHTML = html;
    container.style.display = "block";
}

function validateForm(){
    var fname = document.forms["myForm"]["fname"].value;
    var fcompany= document.forms["myForm"]["fcompany"].value;

    var errors = [];

    if(fname == ""){
        errors.push("you did not fill in fname");
    }
    if(fcompany == ""){
        errors.push("you did not fill in fcompany");
    }

    if(errors.length > 0){
        displayErrors(errors);
        return false;
    } else {
        return true;
    }
}