如何将jQuery验证插件与Ajax按钮提交集成?

时间:2017-12-05 22:42:15

标签: javascript jquery jquery-validate

我创建了一个使用jQuery验证插件的脚本。我的验证脚本工作正常。但是我想在我的Ajax调用之前先验证我的表单。有没有办法将我的Ajax调用与jQuery验证插件集成?

这里有关于插件的一些信息

我的脚本在这里:

jQuery(document).ready(function($) {

  /* set no cache */
  $.ajaxSetup({ cache: false });


var $form = $("form"),
  $successMsg = $(".alert");
$.validator.addMethod("letters", function(value, element) {
  return this.optional(element) || value == value.match(/^[a-zA-Z\s]*$/);
});
$form.validate({
  rules: {
    firstname: {
      required: true,
      minlength: 2,
      letters: true
    },

    lastname: {
      required: true,
      minlength: 2,
      letters: true
    }

  },
  messages: {
    firstname: "Please specify your first name (only letters and spaces are allowed)",
    lastname: "Please specify your last name (only letters and spaces are allowed)"
  },
  submitHandler: function() {
    $successMsg.show();
  }
});

  $('#submitButton').click( function(e) {

      $.ajax({

          url: '/form/submit',
          type: 'post',
          dataType: 'json',
          data: $('#Form').serialize(),
          success: function(data) {
            // message



          },
          error: function(xhr, status, error){

          //message        

          } 

          // Prevent default form action

      });


  });



});

我的HTML代码在这里:

<form id="Form">
    <input class="fname" id="firstname" name="firstname" type="text" />
    <input class="lname" id="lastname" name="lastname" type="text" />
    <button class="btn btn-default" id="submitButton" type="submit">Submit</button>
</form>

0 个答案:

没有答案