Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form not getting submitted with jQuery validation

Ive got a little problem while using jQuery validation plugin in on my .net/MVC projects: The validation generally works all fine, the issue arises at the time of submitting: I want form not be submitted when there are any validation errors in it and for this I set debug:true;

But after setting it to true when the submit button becomes unresponsive, even when everything is fine i.e. no validation errors, nothing just happens while clicking the submit button. And if remove debug:true it submits the form even when there are validation errors in it. I want a solution to this problem, the middle way i.e.: When clicking submit if there are errors it doesn't submits the form and shows errors And if there are no errors then it just simple submits it.

Help plz .. Thank you!

    <script type="text/javascript">
      $(document).ready(function() {
$("#productSubmit").validate( {
  debug : true, rules : {
     prdctttle : {
        maxlength : 50, 
        required : true, 
        onlyChars : true }
     , prdctdscrptn : {
        maxlength : 250, 
        required : true, 
        onlyChars : true }
    }
  , messages : {
     }
  }
); 
}
); 
$.validator.addMethod('onlyChars', function (value) {
return /^[a-zA-Z ,-!]+$/.test(value); }, 'Please enter a valid name with only alphabets');
   $("#productSubmit").validate( {
  submitHandler : function(form) {
     if ($(form).valid()) form.submit(); return false; // prevent normal form posting
     }
  }
);
</script>
like image 646
Maven Avatar asked Oct 27 '11 14:10

Maven


2 Answers

Change your last line to check if the form is valid before submitting:

$("#productSubmit").validate({ 
    submitHandler: function(form) {  
                           if ($(form).valid()) 
                               form.submit(); 
                           return false; // prevent normal form posting
                    }
 });

EDIT: I forgot to add the "return false;" line to stop the form submitting normally (so it only happens when the validation passes).

like image 189
GregL Avatar answered Nov 06 '22 01:11

GregL


GregL's answer is correct for the most part.

What ultimately got this working correctly for me was also the addition of:

onsubmit: false

Final code:

$("#productSubmit").validate({ 
 onsubmit: false,
 submitHandler: function(form) {  
   if ($(form).valid())
   {
       form.submit(); 
   }
   return false; // prevent normal form posting
 }
});

This overrides the default submit behaviour, and handles the final validation check and submission within the submitHandler.

like image 23
PenguinOfwar Avatar answered Nov 06 '22 00:11

PenguinOfwar