Twitter Bootstrap and jQuery Validation Plugin - use class=“control-group error”

前端 未结 2 1033
谎友^
谎友^ 2021-01-22 09:49

I\'ve created a form using the Twitter Bootstrap framework and have integrated the jQuery Validation Plugin. I have one form with a series of yes/no questions with radio buttons

相关标签:
2条回答
  • 2021-01-22 10:40

    Use the errorClass option to set the jQuery Validate plugin to your desired class for errors. This will apply both .control-group and .error classes upon a validation error...

    $(document).ready(function () {
         // initialize the plugin
         $("#inputForm").validate({ 
             errorClass: "control-group error"
         });
    });
    

    http://jsfiddle.net/F28PF/1/

    See documentation for the plugin options: http://jqueryvalidation.org/validate


    EDIT:

    As pointed out, the default behavior puts the errorClass on the message and the input element.

    If you need to toggle the error/valid classes on something else, you would leverage the highlight and unhighlight callback functions.

    $(document).ready(function () {
        // initialize the plugin
        $("#inputForm").validate({
            errorClass: "control-group error",
            highlight: function (element, errorClass, validClass) {
                $(element).closest(".control-group").addClass(errorClass).removeClass(validClass);
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).closest(".control-group").addClass(validClass).removeClass(errorClass);
            }
        });
    });
    
    0 讨论(0)
  • 2021-01-22 10:44

    To use the control-group the way bootstrap was intended to be used, you want to set the value of the surrounding control-group. The accepted answer isn't quite right, you don't want to put control-group on the input itself, but the container. This code should work.

    $("#page-form").validate({
            highlight: function (element, errorClass, validClass) {
                $(element).closest(".control-group").addClass(errorClass).removeClass(validClass);
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).closest(".control-group").addClass(validClass).removeClass(errorClass);
            }
        });
    
    0 讨论(0)
提交回复
热议问题