I have the following block of code:
$(document).ready(function(){
$("#form").submit(function(ev) {
ev.preventDefault();
$.ajax({
type: "POST",
url: "proxy.php",
data: postData,
success: function(data) {
window.location = "thankyou.php";
},
error:function(xhr, ajaxOptions, thrownError){
console.log(xhr.responseText);
}
});
});
$("#form").validate({
//a bunch of validation here
});
});
The issue is that this will continue to post using ajax even though some validation fails.. why is this? Am I using ev.preventDefault() the wrong way? What I want is that for the form to be validated before I send a POST if some validation fails then just cancel, I believe that is through ev.preventDefault()?
I have the following block of code:
$(document).ready(function(){
$("#form").submit(function(ev) {
ev.preventDefault();
$.ajax({
type: "POST",
url: "proxy.php",
data: postData,
success: function(data) {
window.location = "thankyou.php";
},
error:function(xhr, ajaxOptions, thrownError){
console.log(xhr.responseText);
}
});
});
$("#form").validate({
//a bunch of validation here
});
});
The issue is that this will continue to post using ajax even though some validation fails.. why is this? Am I using ev.preventDefault() the wrong way? What I want is that for the form to be validated before I send a POST if some validation fails then just cancel, I believe that is through ev.preventDefault()?
Share Improve this question asked Sep 11, 2011 at 15:57 aherlambangaherlambang 14.4k54 gold badges153 silver badges255 bronze badges2 Answers
Reset to default 6Before doing your ajax request, test if the form is valid:
if (!$(this).valid()) return;
You may want to try the submitHandler option too: http://docs.jquery./Plugins/Validation/validate#options
In the validate
settings you can specify the submitHandler
which takes a function. You can have all the validation login inside submitHandler and return true/false conditionally. Returning false
in submitHandler will not submit the form. Try this
$("form").validate({
submitHandler: function(form) {
// if validation is successfull return true else false.
}
});