Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can JQuery.Validate plugin prevent submission of an Ajax form

I am using the JQuery form plugin (http://malsup.com/jquery/form/) to handle the ajax submission of a form. I also have JQuery.Validate (http://docs.jquery.com/Plugins/Validation) plugged in for my client side validation.

What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour.

I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened.

So what I am I missing that is preventing my desired behaviour? Sample code below....

<form id="searchForm" method="post" action="/User/GetDetails">
        <input id="username" name="username" type="text" value="user.name" />  
        <input id="submit" name="submit" type="submit" value="Search" />   
</form>
<div id="detailsView">
</div>  

<script type="text/javascript">
    var options = {
        target: '#detailsView'
    };
    $('#searchForm').ajaxForm(options);

    $('#searchForm').validate({
    rules: {
    username: {required:true}},
    messages: {
    username: {required:"Username is a required field."}}
    });
</script>
like image 648
berko Avatar asked Sep 26 '08 05:09

berko


2 Answers

... well it's been a while so my situation has changed a little. Currently I have a submitHandler option passed to the Validate() plugin. In that handler I manually use ajaxSubmit. More a workaround than an answer I guess. Hope that helps.

http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html

var v = jQuery("#form").validate({
    submitHandler: function(form) {
        jQuery(form).ajaxSubmit({target: "#result"});
    }
});
like image 44
berko Avatar answered Sep 17 '22 14:09

berko


You need to add a callback function for use with the beforeSubmit event when initializing the ajaxForm():

var options = {
        beforeSubmit: function() {
            return $('#searchForm').validate().form();
        },
        target: '#detailsView'
    };

Now it knows to check the result of the validation before it will submit the page.

like image 79
Lance McNearney Avatar answered Sep 16 '22 14:09

Lance McNearney