superUntitled
superUntitled

Reputation: 22547

jQuery validate before ajaxForm

I am trying to use the "beforeSubmit" option in the jQuery ajaxForm plugin to validate the data, however the form will submit even if there are invalid form fields. Where have I gone wrong? thanks,

$(document).ready(function() { 
function validator(){ 
        $("#commentForm").validate();
}

    $('#commentForm').ajaxForm({ 
        dataType: 'json',
        url: "http://highlandfamilyeyecare.com/contactengine.php",
        beforeSubmit:  validator,
        success:        function(data) { 
            $('ul.form').fadeOut("slow");
            $('ul.form').html(data.formula).slideDown('slow');}
    });
});

And the html:

<ul class="form">


    <li>    
        <form method="post" action="form.php" id="commentForm">

        <label class="white">Your Name</label>
        <input class="text-input required" type="text" name="name" /></li>

    <li>
        <label class="white">Email</label>
        <input class="text-input required email" type="text" name="email"/></li>

    <li>
        <li><input type='submit' value="Submit" />
        </form></li>

</ul>

Upvotes: 3

Views: 11464

Answers (3)

CWF
CWF

Reputation: 2147

The beforeSubmit() function isn't returning anything.

You'll want:

function validator() { 
  return $("#commentForm").validate();
}

presuming that the $('#commentForm").validate() exists and returns true/false correctly.

Upvotes: 6

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

Assuming that the validate() method is the validation plugin, This is the right way of doing it. If there are any errors in the validate method, form will not be submitted.

    $('#commentForm').validate({
        errorClass: "invalidField",
        submitHandler: function() {
            $('#commentForm').ajaxSubmit(ajaxFormOptions);
        }
    });

where ajaxFormOptions are your options for submit.

Upvotes: 2

Dancrumb
Dancrumb

Reputation: 27549

Per the documentation, the validating function must return false in order to prevent form submission.

Upvotes: 3

Related Questions