问题
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?
回答1:
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/
来源:https://stackoverflow.com/questions/19208987/validation-plugin-auto-validate-multiple-forms-on-a-page