50
votes

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();
        } 
10
What happens when you submit?Mantas Vaitkūnas
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
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
Trying the fliespl lines but it still just submits. Updated code in question.Tom

10 Answers

112
votes

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.

19
votes

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);
    },
  });
});
7
votes

You can try doing:

if($("#form").validate()) {
 return true;
} else {
 return false;
}
7
votes
> 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);
            }
        });
    }
});
5
votes

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;
    };
},
4
votes

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
votes

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.

0
votes
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();


    });
  });
0
votes

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

-1
votes

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