为什么表单onsubmit验证没有迭代所有可能性?

时间:2012-12-06 18:05:27

标签: javascript html forms validation onsubmit

第一次在这里发帖,最后一个替代方案是对这种无意义感到更加沮丧。我认为这个代码段没有任何问题,但是onsubmit条件似乎总是返回true,即使我将字段留空(应该在现场验证)。

注意:我的JS功能目前是空白的,还没有那么远。

进一步的调查记录:即使是我写的最后一个案例都是无效的,它只是在我点击提交并完全忽略onsubmit后立即尝试到达结帐页面。

<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> Book registration. </title>
    <script type = "text/javascript" src = 'Script/main.js'></script>
</head>

<body>
    <form method = "POST" action = "Checkout" onsubmit = "validate(this)">      
        <fieldset>
        <legend> Book Registry Access </legend>

        <p> ISBN: <input type = "text" size = "14" name = "ISBN" onchange = "if(this.value != '') ajaxVerif('checkISBN', this.value, this.id);"> </p>
        <p> Title: <input type = "text" size = "32" id = "title" name = "title"> </p>
        <p> Author: <input type = "text" size = "32" id = "author" name = "author"> </p>
        <p> Edition: <input type = "text" size = "2" id = "edition" name = "edition" onchange = "if(this.value != '') ajaxVerif('checkEdi', this.value, this.id);"> </p>
        <p> <input type = "submit"> </p>

        </fieldset>
    </form>
</body>
</html>

    function validate(thisForm)
    {
    if (thisForm.ISBN.value == '') {
                    alert('Please enter a valid ISBN number in the form XXXX-YYYY-ZZZZ');
                    this.ISBN.focus();
                    return false;
                }
    if (thisForm.title.value == '') {
                    alert('Please fill in the title field.');
                    this.title.focus();
                    return false;
                }   
    if (thisForm.author.value == '') {
                    alert('Please fill in the author field.');
                    this.author.focus();
                    return false;
                }
    if (thisForm.edition.value == '') {
                    alert('Please enter a valid edition number.');
                    this.edition.focus();
                    return false;
                }
    alert('Success! This test form is working! (TO BE DELETED!!)');
    return false;
    }
编辑:为清洁而编辑,仍然无法让它工作。所以现在一切都在验证方面有效,显然,返回的是假的。它总是会尝试跳转到下一页(并且因为链接到虚拟页面而失败)。我不太清楚为什么,非常确定我的所有回报都应该没问题。

最终编辑:已修复,我忘记将其写为onsubmit ='return validate(this)'&gt;

1 个答案:

答案 0 :(得分:1)

首先,避免使用内联JavaScript。

通过保持干净的JavaScript代码,您会注意到丢失的}

  if (this.title.value == '') {
    alert('Please fill in the title field.');
    this.title.focus();
    return false;
  }
--^--

更新

  1. 您忘记了return

    onsubmit = "return validate(this);"
             ---^^^^^^---         ---^---
    
  2. 您还忘了用this替换thisForm