53

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
  • 1,747
  • 5
  • 23
  • 39
  • What happens when you submit? – Mantas Vaitkūnas Jul 13 '12 at 11:31
  • At the moment I just echo out all the $key => $value pairs and they keep popping up on my screen even if I only fill out 1/4 questions. – Tom Jul 13 '12 at 11:32
  • I couldn't find `beforeSubmit` as a valid option for $.ajax in the latest version of jquery (v1.7.2). You may want to use the latest version of jquery. That said, Darin's answer is how it ought to be done. That said, if you just can't do what he is suggesting, then replace the last line of your beforeSubmit with the code Fliespl has put up. You need to check the return value of `.validate()` and accordingly either proceed with or cancel ajax request. – Amith George Jul 13 '12 at 11:43
  • Trying the fliespl lines but it still just submits. Updated code in question. – Tom Jul 13 '12 at 12:31

12 Answers12

116

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • But I can still serialize #answers before I validate or stick it right before $.ajax ? – Tom Jul 13 '12 at 11:37
  • `#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. – Darin Dimitrov Jul 13 '12 at 11:39
  • Do 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? – Tom Jul 13 '12 at 15:07
  • Right on target as always, +1 – Suhail Mumtaz Awan Feb 01 '16 at 04:10
  • Right on target² hahah +1 – Zkk Jun 27 '16 at 17:42
  • May 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 Jun 10 '18 at 11:44
21

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 :

  1. on form submit , you prevent the default behavior
  2. if the form is Invalid stop the execution.
  3. 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);
    },
  });
});
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
amd
  • 20,637
  • 6
  • 49
  • 67
  • check if there an error in your browser log, what browser you use ? – amd Jul 13 '12 at 13:14
  • I am using Google Chrome, but I can't find any errors there. Gonna try with this code once more. – Tom Jul 13 '12 at 13:40
  • Won't submit at all now, this goes into the $(document).ready(function(){ right? – Tom Jul 13 '12 at 13:43
  • yes it should be in the document ready block, have you added an ID to your form ?, your form must have `
    ...
    `
    – amd Jul 13 '12 at 14:00
  • Now 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 Jul 13 '12 at 14:05
  • Seems 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 Jul 13 '12 at 14:07
  • Also it changed it's method to get somehow, no idea why O_o – Tom Jul 13 '12 at 14:16
  • may you please extend your answer with `.ajaxSubmit`? – Eugen Konkov Jun 10 '18 at 11:50
7

You can try doing:

if($("#form").validate()) {
 return true;
} else {
 return false;
}
  • I do change display: none on my form as I go dividing it up into several "pages". Think that could cause some problems? – Tom Jul 13 '12 at 12:39
7
> 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);
            }
        });
    }
});
user3655384
  • 71
  • 1
  • 1
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;
    };
},
Erik Grosskurth
  • 3,762
  • 5
  • 29
  • 44
4

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);
                        }            
                    });
                }
            });
3

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.

Mantas Vaitkūnas
  • 704
  • 1
  • 7
  • 17
0
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();


    });
  });
luis
  • 9
  • 1
  • did it like this – luis May 26 '18 at 23:39
  • 1
    Welcome 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. – Tim Diekmann May 27 '18 at 00:18
  • why to use comparison operators? can't we use form.valid() ?? that would be more efficient. – Mujtaba May 20 '21 at 16:16
0

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()

carlin.scott
  • 6,214
  • 3
  • 30
  • 35
0
$("#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

  1. change default error message
  2. How do I include the field label in a JQuery Validate error message
Harsh Patel
  • 1,032
  • 6
  • 21
0

HTML Form:

<div class="w3-padding w3-flat-clouds">
         <p><label>Your Name:</label><input id = 'name' class="w3-input w3-border" type="text" name = 'enter-name' placeholder = "Enter your Name" required></p>
         <p><label>Your Email:</label><input id = 'e-mail' class="w3-input w3-border" type="text" name = 'enter-email' placeholder = "Enter your email" required></p>
         <p><label>Your Message:</label><textarea id = 'message' style = 'height: 80px;' class="w3-input w3-border" name = 'enter-message' placeholder = "Enter your message..." required></textarea></p>
         <button class = 'w3-button w3-btn w3-black w3-hover-green' id = 'sub-btn'>submit</button>
      </div>

AJAX:

   $(document).ready(() => {
        $('#sub-btn').click(() => {
            var nameInsert = document.getElementById('name').value;
            var emailInsert = document.getElementById('e-mail').value;
            var messageInsert = document.getElementById('message').value;

            var atTheRate = emailInsert.indexOf("@");
            var dotPosition = emailInsert.lastIndexOf(".");
            if(atTheRate < 1 || dotPosition < 6)
            {
              alert(nameInsert + ' Please Provide Your Proper Email!');
              return false;      //Prevents your form to being submit.
            }
            else
            {
            $.ajax({  
                url: '/send-details',
                method: 'GET',
                data: {
                    nameInsert: nameInsert,
                    emailInsert: emailInsert,
                    messageInsert: messageInsert
                },
                success: (successObj) => {
                  var successResult = JSON.parse(successObj);
                    if(successResult)
                    {
                        console.log(successResult);
                        alert('Thank You ' + nameInsert + '! Your Message Received Successfully!');
                    }
                    else
                    {
                        console.log('Message Insertion failed!');
                        alert('Message Insertion failed!');
                    }
                }
            });
            return true;    //Allows you to submit.
          }
        });
   });
-1

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");
        }
    });
});
linktoahref
  • 7,812
  • 3
  • 29
  • 51
jforjs
  • 465
  • 1
  • 4
  • 11