Can JQuery.Validate plugin prevent submission of an Ajax form

By : berko
Source: Stackoverflow.com
Question!

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>
By : berko


Answers

Just as a first pass, I'm wondering why the line

$("form").validate({

doesn't refer to $("searchform"). I haven't looked this up, or tried it, but that just seems to be a mismatch. Wouldn't you want to call validate on the appropriate form?

Anyway, if this is completely wrong, then the error isn't immediately obvious. :)



$('#contactform').ajaxForm({
  success : FormSendResponse, 
  beforeSubmit:  function(){
    return $("#contactform").valid();
  }
});


$("#contactform").validate();   

Above code worked fine for me.



ok, this is an old question but i will put our solution here for posterity. i personally classify this one as a hack-trocity, but at least it's not a hack-tacu-manjaro

<script type="text/javascript">
    var options = {
        target: '#detailsView'
    };

// -- "solution" --
$('#searchForm').submit(function(event) {
  this.preventDefault(event); // our env actually monkey patches preventDefault
                              // impl your own prevent default here
                              // basically the idea is to bind a prevent default
                              // stopper on the form's submit event
});
// -- end --

    $('#searchForm').ajaxForm(options);

    $('#searchForm').validate({
      rules: {
      username: {required:true}},
      messages: {
      username: {required:"Username is a required field."}}
    });
</script>
By : duggi


This video can help you solving your question :)
By: admin