Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

jquery - Validation plugin - Auto validate multiple forms on a page

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...