Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation plugin - Auto validate multiple forms on a page

Tags:

Currently I need to validate every form like this:

    $(document).ready(function () {         $('#admin_settings_general').validate({             rules: {                 admin_settings_application_title: {                     required: true                 }             },             highlight: function (element) {                 $(element).closest('.form-group').addClass('has-error');             },             unhighlight: function (element) {                 $(element).closest('.form-group').removeClass('has-error');             }         });     }); 

I want that it automaticly validate the forms for every element with the required tag.

How can I do that?

like image 890
TheNiceGuy Avatar asked Oct 06 '13 12:10

TheNiceGuy


1 Answers

Quote OP:

"I want that it automaticly validate the forms for every element with the required tag."

Quote OP comment:

"i have to call $('#admin_settings_general').validate() for each of the forms currently. How can i call it without limiting it to one form?"


To properly initialize .validate() on all forms on a page, use a common selector such as the form tag itself (or a class). Since you cannot attach .validate() to any jQuery selector that represents multiple form elements, use a jQuery .each(). This is simply how this plugins methods were designed.

$(document).ready(function() {      $('form').each(function() {  // attach to all form elements on page         $(this).validate({       // initialize plugin on each form             // global options for plugin         });     });  }); 

Working DEMO: http://jsfiddle.net/6Fs9y/

like image 158
Sparky Avatar answered Oct 16 '22 22:10

Sparky