验证失败时,表单仍然提交

时间:2012-08-28 15:24:16

标签: jquery html

我有一个表单,即使验证失败,它仍然会提交给控制器。

jQuery的:

$(document).ready(function () {
       $('#commentForm').validate();
});

 $(function () {
     $('#commentForm').submit(function () {
         $('#result').empty();
         $.ajax({
             url: "Action/Index",
             type: "POST",
             data: {
                 name: $('#name').val(),
                 emailAddress: $('#emailAddress').val()
             },
             success: function (result) {
              alert(result);

                 }
             }
         });
       return false;
     });
 });

HTML:

<form class="cmxform" id="commentForm">
<fieldset>
<div id="contactUsName">Your Name<br />
    <input type="text" id="name" class="required" />
</div>
<div id="contactUsEmail">Email Address<br />
    <input type="text" id="emailAddress" class="required email" />
</div>
</fieldset>
</form>

2 个答案:

答案 0 :(得分:3)

您应该使用验证submitHandler属性,如下所示:

$('#commentForm').validate(
  submitHandler: function () {
         $('#result').empty();
         $.ajax({
             url: "Action/Index",
             type: "POST",
             data: {
                 name: $('#name').val(),
                 emailAddress: $('#emailAddress').val()
             },
             success: function (result) {
              alert(result);

             }
           }
         );
       return false;
     });
);

答案 1 :(得分:1)

你有一个额外的括号}

             }
         } //<-- you should remove this one
     });

   return false;