jQuery Form Validation before Ajax submit
Solution 1
You could use the submitHandler
option. Basically put the $.ajax
call inside this handler, i.e. invert it with the validation setup logic.
$('#form').validate({
... your validation rules come here,
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
$('#answers').html(response);
}
});
}
});
The jQuery.validate
plugin will invoke the submit handler if the validation has passed.
Solution 2
first you don't need to add the classRules
explicitly since required
is automatically detected by the jquery.validate plugin.
so you can use this code :
- on form submit , you prevent the default behavior
- if the form is Invalid stop the execution.
- else if valid send the ajax request.
$('#form').submit(function (e) {
e.preventDefault();
var $form = $(this);
// check if the input is valid using a 'valid' property
if (!$form.valid) return false;
$.ajax({
type: 'POST',
url: 'add.php',
data: $('#form').serialize(),
success: function (response) {
$('#answers').html(response);
},
});
});
Solution 3
You can try doing:
if($("#form").validate()) {
return true;
} else {
return false;
}
Solution 4
> Required JS for jquery form validation
> ## jquery-1.7.1.min.js ##
> ## jquery.validate.min.js ##
> ## jquery.form.js ##
$("form#data").validate({
rules: {
first: {
required: true,
},
middle: {
required: true,
},
image: {
required: true,
},
},
messages: {
first: {
required: "Please enter first",
},
middle: {
required: "Please enter middle",
},
image: {
required: "Please Select logo",
},
},
submitHandler: function(form) {
var formData = new FormData($("#image")[0]);
$(form).ajaxSubmit({
url:"action.php",
type:"post",
success: function(data,status){
alert(data);
}
});
}
});
Solution 5
This specific example will just check for inputs but you could tweak it however, Add something like this to your .ajax function:
beforeSend: function() {
$empty = $('form#yourForm').find("input").filter(function() {
return this.value === "";
});
if($empty.length) {
alert('You must fill out all fields in order to submit a change');
return false;
}else{
return true;
};
},
Tom
Updated on July 09, 2022Comments
-
Tom almost 2 years
JavaScript bit:
$(document).ready(function() { $('#form').submit(function(e) { e.preventDefault(); var $form = $(this); // check if the input is valid if(! $form.valid()) return false; $.ajax( { type:'POST', url:'add.php', data:$('#form').serialize(), success:function(response) { $("#answers").html(response); } }); }) });
HTML bit:
<input type="text" name="answer[1]" class="required" /> <input type="text" name="answer[2]" class="required" />
So this is the code I am trying to use. The idea is to get all my inputs validated before I send my form with Ajax. I've tried numerous versions of this now but every time I end up with submitting even though the form is not entirely filled out. All my inputs are of the "required" class. Can anyone see what I am doing wrong?
Also, I depend on class-based requirements as my input names are generated with php so I can never be sure what name[id] or input types I get.
I show/hide questions as I go through it in "pages".
<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>
JS:
function toggleVisibility(newSection) { $(".section").not("#" + newSection).hide(); $("#" + newSection).show(); }
-
Tom almost 12 yearsBut I can still serialize #answers before I validate or stick it right before $.ajax ?
-
Darin Dimitrov almost 12 years
#answers
is your result div. If you want to send the form input field values along with the AJAX request, use the.serialize()
method, exactly as shown in my answer:data: $(form).serialize()
=> inside the submit handler. -
Tom almost 12 yearsI do change display: none on my form as I go dividing it up into several "pages". Think that could cause some problems?
-
amd almost 12 yearscheck if there an error in your browser log, what browser you use ?
-
Tom almost 12 yearsI am using Google Chrome, but I can't find any errors there. Gonna try with this code once more.
-
Tom almost 12 yearsWon't submit at all now, this goes into the $(document).ready(function(){ right?
-
amd almost 12 yearsyes it should be in the document ready block, have you added an ID to your form ?, your form must have
<form id='form'>... <input type=submit value=submit></form>
-
Tom almost 12 yearsNow I am getting somewhere. I only had a input type="button". Still it only requires my checkboxes. It ignores the textboxes and radiobuttons. Could it be because they are hidden? I hide older questions and only present the current "page"
-
Tom almost 12 yearsSeems it cannot operate over more than 1 "page". Added a textbox at the last "page" which it did require. Wonder if there is any way around this O_o
-
Tom almost 12 yearsAlso it changed it's method to get somehow, no idea why O_o
-
Tom almost 12 yearsDo you think there's any chance that splitting up the form in several divs that are hidden/shown as the user goes through the form could have anything to do with me not getting this code to work?
-
Suhail Mumtaz Awan over 8 yearsRight on target as always, +1
-
Zkk about 8 yearsRight on target² hahah +1
-
Deepa MG over 6 yearsThis answer is quite clearly explained for beginers... Thanks! But is this also validate the file attachment !! How !!
-
luis about 6 yearsdid it like this
-
Tim Diekmann about 6 yearsWelcome to Stack Overflow! Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
-
Eugen Konkov about 6 yearsMay you please extend you answer and shed the light on
.ajaxSubmit
. When I use it instead of$.ajax
the common submit occur. How to prevent that? -
Eugen Konkov about 6 yearsDoes
jquery.form.js
required? -
Eugen Konkov about 6 yearsmay you please extend your answer with
.ajaxSubmit
? -
Mujtaba about 3 yearswhy to use comparison operators? can't we use form.valid() ?? that would be more efficient.