jQuery Validate stop form submit with ajax

陌路散爱 提交于 2019-12-18 09:54:10

问题


So,

I have been using jQuery Validate for from validation and I have stumbled across something that puzzling me.

I have the form validating properly which is working right but this form is in a modal. Now big deal but when I hit submit, it activates an ajax post, the modal goes away and a DIV on the page updates.

What happens is: The validation works but the ajax still posts.

First: Here is the Javascript validation:

<script>


$(function() {

  $.validator.setDefaults({
    errorClass: 'help-block',
    highlight: function(element) {
      $(element)
        .closest('.form-group')
        .addClass('has-error');
    },
    unhighlight: function(element) {
      $(element)
        .closest('.form-group')
        .removeClass('has-error');
    },
    errorPlacement: function (error, element) {
      if (element.prop('type') === 'radio') {
        error.insertAfter(element.parent());
      } else {
        error.insertAfter(element);
      }
    }
  });






  $("#testForm").validate({
    rules: {
      contractNumber: {
        required: true
      },

      dateFrom: {
        required: true,
        nowhitespace: true
      },

      dateTo: {
        required: true,
        nowhitespace: true
      },

      contractType: {
        required: true
      }
    },

    messages: {
      contractNumber: {
        required: 'Please enter a contract number.'
    }
}
  });

});

</script>




<script>
    $(document).ready(function() {
    $("#testForm").submit(sendForm)
    });

    function sendForm() {
    $.post('index.cfm/candidate/putContract',$("#testForm").serialize(),function(data,status)
    {   
        $('#addContract').modal('hide');
        $("#contractView").html(data)
        });
    return false
    }
</script>

This script hides the modal, then posts the results.

What I would like to happen is the validation happen and only pushing when the validation is passed.

http://jsfiddle.net/mwoods98/bh6t2h78/

Here is a fiddle that was setup. It does not post.

Thanks in advance!


回答1:


The validation works but the ajax still posts.

That's because your submit event handler is bypassing the plugin. You will not need to capture the submit event as that is handled automatically by the plugin. As per the documentation, the ajax belongs inside of the plugin's submitHandler option.

Replaces the default submit. The right place to submit a form via Ajax after it is validated.

submitHandler: function(form) {
    // ajax goes here
    $.post(....);
    return false;
}

DEMO: http://jsfiddle.net/bh6t2h78/2/

In order to get your jsFiddle working properly, I had to comment out your nowhitespace rule declarations since this method is presently undefined.



来源:https://stackoverflow.com/questions/32771986/jquery-validate-stop-form-submit-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!