Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery validation not stopping form from being submitted

I'm tearing my hair out here trying to get a jquery validation to play nicely with my form.

The validation does not appear to be working. The form just submits itself to the page. I can briefly see the validation error messages appearing before the page submits...

My code:

//HTML form
<form id="form_scheduleEvent" name="form_scheduleEvent">
  <label for="name">Name:</label><input class="short" type="text" name="name" id="name" />
  <label for="address">Address:</label><input type="text" name="address" id="address" />
  <label for="phone">Phone:</label><input type="text" name="phone" id="phone" />
  <label for="comments">Comments:</label><textarea name="comments" id="comments" /></textarea>
  <input type="submit" id="submitRequest" value="Add"/>
</form>


//jquery
//Validation rules
$('#form_scheduleEvent').validate({
rules: {
    name : {required: true, maxlength: 45},
    address : {required: true, maxlength: 45},
    phone : "required"
}
});


$('#submitRequest').click(function(){
   $.ajax({
       type: "POST",
       url: "common/ajax_event.php",
       data: formSerialized,
       timeout:3000,
       error:function(){alert('Error');},
       success: function() {alert('It worked!');}
  });

 return false;
});

I tried updating to the latest version of both jquery and jquery.validation....

Any help would be appreciated! Thanks.

Update

//The validation is working, but I can't even get the alert to show....
$('#form_scheduleEvent').validate({
 rules: {
   name : {required: true, maxlength: 45}, 
   address : {required: true, maxlength: 45},
   phone : "required",
   submitHandler: function(){
     alert('test');
   }
 }
});
like image 433
Matt Avatar asked Nov 29 '22 17:11

Matt


2 Answers

You should move your AJAX submit call to be fired off by the submit callback in the validate plugin:

$('#form_scheduleEvent').validate({
rules: {
    name : {required: true, maxlength: 45},
    address : {required: true, maxlength: 45},
    phone : "required",
    submitHandler: function(form) { DoSubmit(); }
}
});


function DoSubmit(){
   $.ajax({
       type: "POST",
       url: "common/ajax_event.php",
       data: formSerialized,
       timeout:3000,
       error:function(){alert('Error');},
       success: function() {alert('It worked!');}
  }
like image 111
Paddy Avatar answered Dec 10 '22 21:12

Paddy


Thanks everyone for their reply.

I ended up wrapping the ajax call part of my original code in the following code:

if($('#form_scheduleEvent').valid() == true){
  //Process ajax request...
}
return false;
like image 41
Matt Avatar answered Dec 10 '22 21:12

Matt