JQuery:表单在JQuery Validation之前提交的原因

时间:2016-11-01 03:56:58

标签: jquery ajax forms

我有一个带有输入和输入的网页表单。 select.I有一个Ajax发送这些字段的数据。在提交之前我执行验证以检查空字段。但是,代码不起作用。我认为表单提交事件使用其默认值保留字段在执行验证之前。如何在submit.please帮助之前强制检查验证。

以下是代码:

    function validate_fields() {

    var empty_inputs = $('.mandatory').filter(function() {
        return !$(this).val();
    }).length;
    //Checking if any Empty input or select that has class mandatory
    if (empty_inputs > 0) {
        $('form').find('input.mandatory, select.mandatory').each(function() {
            if ($(this).val() == '' || $(this).val() == null) { //Change the color if empty input or select
                $(this).css('background-color', '#FFCECE');
            } else {
                $(this).css('background-color', 'transparent');
            };

        });
        return false;
    } else {
        return true;
    }

}

$('#button_save').click(function() {

            $("form").on("submit", function(event) {

                var status;
                status = validate_fields();
                // if fuction validate_fields return false then Stop submit
                if (status == false) {
                    return false;
                }

                var dt = $(this).serializeArray();
                event.preventDefault();

                //This Ajax Post the Input data if validation return true.
                $.ajax({

                    url: 'send_data.php',
                    type: "post",
                    async: true,
                    data: dt,
                    dataType: 'html',
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                    success: function(data) {

                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        console.log(textStatus, errorThrown);

                    }

                });

            });

3 个答案:

答案 0 :(得分:1)

**you can use this as a Template**

// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
  $("form[name='registration']").validate({
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      },
      password: {
        required: true,
        minlength: 5
      }
    },
    // Specify validation error messages
    messages: {
      firstname: "Please enter your firstname",
      lastname: "Please enter your lastname",
      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 5 characters long"
      },
      email: "Please enter a valid email address"
    },
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {
      form.submit();
    }
  });
});

答案 1 :(得分:1)

我认为您需要做的是在验证表单属性之前更改代码的顺序,防止表单的默认行为。

$('#button_save').click(function() {

            $("form").on("submit", function(event) {
                event.preventDefault();
                var status;
                status = validate_fields();

..........
     });

});

答案 2 :(得分:1)

我认为您可以删除按钮点击事件并直接使用表单提交事件。

<强> HTML

<form method="post">
  <input type="text" class="mandatory"/>
  <select class="mandatory">
    <option>One</option>
    <option>Two</option>
  </select>

  <button type="submit">Submit</button>
</form>

<强> JS

$(function () {

    function validate_fields() {

     var empty_inputs = $('.mandatory').filter(function() {
        return !$(this).val();
     }).length;
     //Checking if any Empty input or select that has class mandatory
     if (empty_inputs > 0) {
        $('form').find('input.mandatory, select.mandatory').each(function()     {
            if ($(this).val() == '' || $(this).val() == null) { //Change the color if empty input or select
                $(this).css('background-color', '#FFCECE');
            } else {
                $(this).css('background-color', 'transparent');
            };

        });
        return false;
    } else {
        return true;
    }

  }

    $("form").on("submit", function(event) {
    var status;
    status = validate_fields();

    // if fuction validate_fields return false then Stop submit
    if (status == false) {
      return false;
    }

    var dt = $(this).serializeArray();
    event.preventDefault();


    //This Ajax Post the Input data if validation return true.
     $.ajax({

       url: 'send_data.php',
       type: "post",
       async: true,
       data: dt,
       dataType: 'html',
       contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
       success: function(data) {

       },
       error: function(jqXHR, textStatus, errorThrown) {
         console.log(textStatus, errorThrown);

       }

     });

  });
});

查看此https://jsfiddle.net/gxj3vL5c/3/