【问题标题】:Ajax is bypassing JQuery validationAjax 绕过了 JQuery 验证
【发布时间】:2013-04-30 18:24:35
【问题描述】:

我目前在我的表单上使用 Jquery 验证。但是我也在使用ajax提交。当我单击提交时,尽管我进行了验证,但没有填写输入,表单仍会通过。请指教。

这是我的代码:

Jquery 验证码:

$(function() {
   $("#mytestform" ).validate({
           rules: {
                   aname: {
                           required: true,
                           minlength: 4,
                           maxlength: 20
                   },
                   req: {
                           required: true,
                           minlength: 4                        
                                              },
                        email: {
                               required: true,
                               email: true
                       },                      
           },

           messages: {
                       email: "Enter a valid email address.",
             },
   });
});

</script>


Here is my ajax code:
<script language="Javascript">
   //var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;  
    //alert (dataString);return false;  
    $("#mytestform").submit(function(event) {
        // Assign handlers immediately after making the request,// and remember the jqxhr object for this request
    event.preventDefault();
    var jqxhr = $.post("testme.php", $("#mytestform").serialize());
    jqxhr.done(function(data, textStatus, jqXHR) { 
        //alert(textStatus + " second success " + data); 
        $('<p>Contact Form Submitted!</p>').prependTo('#mytestform');

     }
    );      
    jqxhr.fail(function(jqXHR, textStatus, errorThrown) { alert("There was an issue with your form" + " " + errorThrown); });       
}); 

这是我的html:

<div id = "dvdform"> <!-- begin of form -->
<form id="mytestform" name="mytestform" action="testme.php" method="post">
<fieldset>
<legend><strong>Contact Me</strong></legend>
<div id= "formsection">
<div><p> <label for="aname">Name:&nbsp;</label> <input name="aname" class="boxform" minlength=4 />
                   </p> </div>
<div><p><label for="email">E-mail</label> <input type="text" name="email"  maxlength="40"class="boxform" />
</p></div>
<div><p><label for="city">City</label> <input type="text" name="city"   class="boxform" maxlength="40" />
<br />
</p></div>
<div><p><label for="country">Company</label> <input type="text" name="country"  class="boxform" maxlength="40" />
<br />
</p></div>
<p><label for="country">Comments</label> <textarea name="req" class="required" cols="35" rows="30" style="height:100px;"> </textarea><br />
<br />
</p>

<div align="center" class="submitbox"> 
  <input type="submit" value="SUBMIT" style="width:175px; height:20px;"> 
</div>
</div> 
<!-- End of Form Section -->
</fieldset>
 </form> 
</div>

COMBINING IT using the submithandler still does not work:
$(function() {
   $("#mytestform" ).validate({
           rules: {
                   aname: {
                           required: true,
                           minlength: 4,
                           maxlength: 20
                   },
                   req: {
                           required: true,
                           minlength: 4                        
                                              },
                        email: {
                               required: true,
                               email: true
                       },                      
           },

           messages: {
                       email: "Enter a valid email address.",
             },

             submitHandler: function(form) {
                var jqxhr = $.post("testme.php", $("#mytestform").serialize());
        jqxhr.done(function(data, textStatus, jqXHR) { 
            //alert(textStatus + " second success " + data); 
            $('<p>Contact Form Submitted!</p>').prependTo('#mytestform');

         }
        );      
        jqxhr.fail(function(jqXHR, textStatus, errorThrown) { alert("There was an issue with your form" + " " + errorThrown); });       
    });  
   });
});

</script>

【问题讨论】:

    标签: jquery ajax forms plugins jquery-validate


    【解决方案1】:

    此插件不需要外部 click 或 submit 处理程序。一切都是自动处理的。您将ajax 放在submitHandler 回调函数中,然后在触发ajax 函数之前可靠地验证表单。您还需要一个return false 作为submitHandler 回调函数中的最后一行,以阻止表单提交时的默认页面重定向。 (对于更高版本的插件,您似乎不需要return false,因为它在使用回调时已经内置在插件中;使用它不会造成任何伤害。)

    As per documentation:

    submitHandler,回调,默认:默认(原生)表单提交
    表单提交时处理实际提交的回调 有效的。获取表单作为唯一参数。替换默认值 提交。 通过 Ajax 提交表单的正确位置 验证。

    演示:http://jsfiddle.net/Sf5j2/

    $(document).ready(function () {
    
        $('#myform').validate({ // initialize the plugin
            // your rules and/or options,
            submitHandler: function (form) {
                // ajax goes here
                return false; // needed when using ajax
            }
        });
    
    });
    

    【讨论】:

      【解决方案2】:

      您的代码和验证插件都绑定了submit 事件的处理程序。我不认为验证的处理程序会首先运行。

      相反,将您的 AJAX 调用实现为验证插件的 submitHandler 选项。这确保它执行验证,并且仅在验证成功时运行 AJAX 代码。

      $(function () {
          $("#mytestform").validate({
              rules: {
                  aname: {
                      required: true,
                      minlength: 4,
                      maxlength: 20
                  },
                  req: {
                      required: true,
                      minlength: 4
                  },
                  email: {
                      required: true,
                      email: true
                  }
              },
      
              messages: {
                  email: "Enter a valid email address."
              },
      
              submitHandler: function (form) {
                  var jqxhr = $.post("testme.php", $("#mytestform").serialize());
                  jqxhr.done(function (data, textStatus, jqXHR) {
                      //alert(textStatus + " second success " + data); 
                      $('<p>Contact Form Submitted!</p>').prependTo('#mytestform');
      
                  });
                  jqxhr.fail(function (jqXHR, textStatus, errorThrown) {
                      alert("There was an issue with your form" + " " + errorThrown);
                  });
              }
          });
      });
      

      FIDDLE

      【讨论】:

      • @JacklynN,您需要一个return false 作为submitHandler 回调函数内的最后一行,以阻止提交时的正常页面重定向。请参阅我的演示答案。
      • @Sparky 您链接到的文档中的示例不返回 false。
      • @Barmar,文档有时可能很粗略。除此之外,开发人员最近提到可能消除了处理程序中对return false 的需要。我将它留在我的示例中,因此读者/用户不必担心版本。
      • @Barmar,是的,在最新版本的插件中,return false 的需求似乎已过时。无论如何,您的答案也是正确的,并且 OP 的代码应该可以正常工作。
      • @Sparky 仅供参考,我刚刚检查了 1.9.0,它也不需要 return false。
      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多