jQuery Form Validation before Ajax submit
JqueryAjaxJquery ValidateValidationJquery Problem Overview
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();
}
Jquery Solutions
Solution 1 - Jquery
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 - Jquery
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 - Jquery
You can try doing:
if($("#form").validate()) {
return true;
} else {
return false;
}
Solution 4 - Jquery
> 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 - Jquery
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;
};
},
Solution 6 - Jquery
I think submitHandler with jquery validation is good solution. Please get idea from this code. Inspired from @Darin Dimitrov
$('.calculate').validate({
submitHandler: function(form) {
$.ajax({
url: 'response.php',
type: 'POST',
data: $(form).serialize(),
success: function(response) {
$('#'+form.id+' .ht-response-data').html(response);
}
});
}
});
Solution 7 - Jquery
I think that i first validate form and if validation will pass, than i would make ajax post. Dont forget to add "return false" at the end of the script.
Solution 8 - Jquery
function validateForm()
{
var a=document.forms["Form"]["firstname"].value;
var b=document.forms["Form"]["midname"].value;
var c=document.forms["Form"]["lastname"].value;
var d=document.forms["Form"]["tribe"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
{
alert("Please Fill All Required Field");
return false;
}
else{
$.ajax({
type: 'post',
url: 'add.php',
data: $('form').serialize(),
success: function () {
alert('Patient added');
document.getElementById("form").reset();
}
});
}
}
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
validateForm();
});
});
Solution 9 - Jquery
You need to trigger form validation before checking if it is valid. Field validation runs after you enter data in each field. Form validation is triggered by the submit event but at the document level. So your event handler is being triggered before jquery validates the whole form. But fret not, there's a simple solution to all of this.
You should validate the form:
if ($(this).validate().form()) {
// do ajax stuff
}
https://jqueryvalidation.org/Validator.form/#validator-form()
Solution 10 - Jquery
$("#myformId").submit(function (event) {
// submit modal form of create & edit
event.preventDefault();
formObj = $(this);
// check the form input is valid or not if not valid then return false;
if (!formObj.validate().form()) return false;
data = $(formObj).serializeArray();
// do stuff with ajax or anything else what you wants
});
explainantion:- first validate form and if validation will pass, then call ajax request otherwise stop execution using return false;
var validator = $( "#myform" ).validate();
Validates the form, returns true if it is valid, false otherwise. So, we need to check just if (!formObj.validate().form())
for more details see here documentation
I share customization option of validate function
$(function () {
$('form.needs-validation').each(function() { // <- selects every <form> on page which contains .needs-validation class
var validator = $(this).validate({
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
});
});
for more details about to customize the JQuery validation see here
> for Customizing the default Validation Messages see below answers URLs that was really helpful to me
Solution 11 - Jquery
Form native JavaScript checkValidity
function is more then enough to trigger the HTML5
validation
$(document).ready(function() {
$('#urlSubmit').click(function() {
if($('#urlForm')[0].checkValidity()) {
alert("form submitting");
}
});
});