即使在Javascript验证失败后,表单仍在提交?

时间:2014-06-09 22:15:40

标签: javascript forms validation submit

我有一个名为的表格:

<span class="aligncenter button"><a href="#" onclick="submitForm('newIncident');">Submit</a></span>

我在这里有一个JavaScript函数:

if (myForm == 'newIncident')
    {
        var vDemAge = document.forms['newIncident']['demAge'].value;
        var vBibNumber = document.forms['newIncident']['bibNumber'].value;

        // Run through validations before submitting form
        validateTime();
        validateDate();
        validateAge();
        validateGender();
        validateLocation();
        validateType();
        validateDisposition();

        if (vDemAge == 'Age' || vDemAge == '')   // If Age is not entered, set the value to be blank
            {
                document.forms['newIncident']['demAge'].value = '';
            }
        if (vBibNumber == 'Bib #' || vBibNumber == '')  // If Bib # is not entered, set the value to blank
            {
                document.forms['newIncident']['bibNumber'].value = '';
            }
        document.getElementById(myForm).submit();
    }
else
    {
        document.getElementById(myForm).submit();
    }

所以我将每个验证作为一个单独的函数,我在提交表单时按顺序调用。如果我注释掉&#34; document.getElementById(myForm).submit();&#34;,则验证按预期运行。但是,如果我将其取消注释,即使验证失败,也会每次都提交。我怎样才能阻止这种情况发生?

谢谢!

编辑: 所以这是我正在运行的验证之一。他们的结构都是一样的。某处我应该返回一个布尔值true / false?我将如何在下面插入这个?

function validateDisposition()
{
    var vIncidentDisposition = document.forms['newIncident']['incidentDisposition'].value;
    if (vIncidentDisposition == '')
        {
            document.forms['newIncident']['incidentDisposition'].className = 'required';
        }
    else
        {
            document.forms['newIncident']['incidentDisposition'].className = 'formborder';
        }
}

2 个答案:

答案 0 :(得分:0)

假设你的验证函数返回一个bool,你应该有类似

的东西
if( validateTime() && validateDate() && validateAge()... etc ) {
    if (vDemAge == 'Age' || vDemAge == '')   // If Age is not entered, set the value to be blank
        {
            document.forms['newIncident']['demAge'].value = '';
        }
    if (vBibNumber == 'Bib #' || vBibNumber == '')  // If Bib # is not entered, set the value to blank
        {
            document.forms['newIncident']['bibNumber'].value = '';
        }
    document.getElementById(myForm).submit();
}

答案 1 :(得分:0)

我搞定了!布尔的想法让我走上了正确的道路。谢谢!

我刚刚添加了一个&#34;返回true&#34;和&#34;返回false&#34;对每个验证,然后使用&#34;&amp;&amp;&#34;如果要在myform中构建逻辑&#34;如果&#34;。如果它没有通过所有这些,那么其他人会做一个&#34;返回false&#34;。像魅力一样工作!