问题
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