最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery preventDefault to do validation before POST - Stack Overflow

programmeradmin3浏览0评论

I have the following block of code:

  $(document).ready(function(){
  $("#form").submit(function(ev) {
                ev.preventDefault();

   $.ajax({
                        type: "POST",
                        url: "proxy.php",
                        data: postData,
                        success: function(data) {
                                 window.location = "thankyou.php";
                        },
                        error:function(xhr, ajaxOptions, thrownError){
                                 console.log(xhr.responseText);
                        }
                });
      });

  $("#form").validate({

        //a bunch of validation here
  });
});

The issue is that this will continue to post using ajax even though some validation fails.. why is this? Am I using ev.preventDefault() the wrong way? What I want is that for the form to be validated before I send a POST if some validation fails then just cancel, I believe that is through ev.preventDefault()?

I have the following block of code:

  $(document).ready(function(){
  $("#form").submit(function(ev) {
                ev.preventDefault();

   $.ajax({
                        type: "POST",
                        url: "proxy.php",
                        data: postData,
                        success: function(data) {
                                 window.location = "thankyou.php";
                        },
                        error:function(xhr, ajaxOptions, thrownError){
                                 console.log(xhr.responseText);
                        }
                });
      });

  $("#form").validate({

        //a bunch of validation here
  });
});

The issue is that this will continue to post using ajax even though some validation fails.. why is this? Am I using ev.preventDefault() the wrong way? What I want is that for the form to be validated before I send a POST if some validation fails then just cancel, I believe that is through ev.preventDefault()?

Share Improve this question asked Sep 11, 2011 at 15:57 aherlambangaherlambang 14.4k54 gold badges153 silver badges255 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Before doing your ajax request, test if the form is valid:

if (!$(this).valid()) return;

You may want to try the submitHandler option too: http://docs.jquery./Plugins/Validation/validate#options

In the validate settings you can specify the submitHandler which takes a function. You can have all the validation login inside submitHandler and return true/false conditionally. Returning false in submitHandler will not submit the form. Try this

$("form").validate({
    submitHandler: function(form) {
        // if validation is successfull return true else false.
    }
});
发布评论

评论列表(0)

  1. 暂无评论