jQuery validate: submitting form only when fields are validated

笑着哭i 提交于 2019-12-11 02:29:37

问题


I'm using the code below to validate my form. The validation is going great but I have a problem when submitting the form. And the problem is: the form is submitted to the php file everytime the "Send form" button is clicked, no matter if the form is not validated.

How can I fix that?

I've been researching submitHandler but I don't know how to use it with ajax and serialize..

Thanks a lot!

<script>
$(document).ready(function(){
   $("#form").validate({
      rules: {
         name: {
           required: true
         },
         lname: {
           required: true
         }

      },
      messages: {
         name: {
           required: "* required"
         },
         lname: {
           required: "* required"
         }
      }

   }); //end validate

  $('#form').submit(function() {

    theUrl = 'form.php';

     var params = $(this).serialize();
    $.ajax ({
            type: "POST",
            url: theUrl,
            data: params,
            processData:false,
            async:false,
            success: function(result) {

                //if (data != "") alert (data);
            }
    });
    //return false;
  }); //end submit

});    //end document ready 



</script>

回答1:


You need to place your AJAX request code in the submitHandler parameter of the validate plugin. Currently the AJAX request is being run on the submit() event, parrallel to any validation result. Try this:

$(document).ready(function(){
    $("#form").validate({
        rules: {
            name: { required: true },
            lname: { required: true }
        },
        messages: {
            name: { required: "* required" },
            lname: { required: "* required" }
        },
        submitHandler: function(form) {
            theUrl = 'form.php';
            var params = $(form).serialize();

            $.ajax ({
                type: "POST",
                url: theUrl,
                data: params,
                processData: false,
                async: false,
                success: function(result) {
                    //if (data != "") alert (data);
                }
            });
        }
    }); //end validate
});

More information on the submitHandler parameter.



来源:https://stackoverflow.com/questions/8383690/jquery-validate-submitting-form-only-when-fields-are-validated

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