Validation plugin - Auto validate multiple forms on a page

╄→尐↘猪︶ㄣ 提交于 2020-01-27 15:48:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!