How to make select2 work with jquery.validation plugin?

后端 未结 15 617
北荒
北荒 2020-12-01 02:40

I\'m trying to validate select2 field using jquey.validation plugin but nothing happens.

I want to make select required field.

I\'m using this custom validat

15条回答
  •  半阙折子戏
    2020-12-01 03:24

    I have detailed this in a blog post: http://chadkuehn.com/jquery-validate-select2/

    When you place a Select2 on a SELECT tag it hides the original element. So in the validation plugin you must adjust the proper wrapping markup when highlighting and unhighlighting.

        highlight: function (element, errorClass, validClass) {
            var elem = $(element);
            if (elem.hasClass("select2-offscreen")) {
                $("#s2id_" + elem.attr("id") + " ul").addClass(errorClass);
            } else {
                elem.addClass(errorClass);
            }
        },
    
        unhighlight: function (element, errorClass, validClass) {
            var elem = $(element);
            if (elem.hasClass("select2-offscreen")) {
                $("#s2id_" + elem.attr("id") + " ul").removeClass(errorClass);
            } else {
                elem.removeClass(errorClass);
            }
        }
    

    View a DEMO here.

提交回复
热议问题