简体   繁体   English

如何使 select2 与 jquery.validation 插件一起工作?

[英]How to make select2 work with jquery.validation plugin?

I'm trying to validate select2 field using jquey.validation plugin but nothing happens.我正在尝试使用 jquey.validation 插件验证 select2 字段,但没有任何反应。

I want to make select required field.我想选择必填字段。

I'm using this custom validation function:我正在使用这个自定义验证功能:

$.validator.addMethod("requiredcountry", function(value, element, arg){
              return arg != value;
         }, "Value must not equal arg.");

and this is the rule:这是规则:

rules:
{
 country:
 {
         required: true,
         requiredcountry: ""
 }
}

What select2 field should I use for the rule to match?我应该使用哪个 select2 字段来匹配规则?

I appreciate any idea how to make select2 working together with jquery.validation我很欣赏如何让 select2 与 jquery.validation 一起工作的任何想法

10x 10倍

Just add ignore: [], in Your form validation function.只需在您的表单验证功能中添加ignore: [], It will enable hidden field validation.So You will get validation for Select 2它将启用隐藏字段验证。因此您将获得 Select 2 的验证

$("#ContactForm").validate({
  ignore: [],       
  rules: {
    //Rules
  },
  messages: {
    //messages
  }
});

As a tip, please consider that the validate js bind itself to changes of select not select 2. This cause problem in below case:作为提示,请考虑验证 js 将自身绑定到 select not select 2 的更改。这会导致以下情况出现问题:

  1. There is a required select box which is converted to select2有一个必需的select box被转换为select2
  2. You click the submit and the error shows that the select box is required.您单击提交,错误显示需要选择框。
  3. You select some option from select 2.您从选择 2 中选择一些选项。
  4. The validation error does not hide automatically验证错误不会自动隐藏

You can fix it with:您可以使用以下方法修复它:

     $("select").on("select2:close", function (e) {  
        $(this).valid(); 
    });

In Addition to ABIRAMAN's answer here is some code that除了 ABIRAMAN 的回答,这里还有一些代码

  • Makes the select2 box red when errors appear出现错误时使 select2 框变为红色
  • List the error below the select2 box列出 select2 框下方的错误

<style>
  span.error{
    outline: none;
    border: 1px solid #800000;
    box-shadow: 0 0 5px 1px #800000;
  }
</style>

<script>
 $("#form").validate({
     rules: {
       email: "required"
     },
     highlight: function (element, errorClass, validClass) {
       var elem = $(element);
       if (elem.hasClass("select2-hidden-accessible")) {
           $("#select2-" + elem.attr("id") + "-container").parent().addClass(errorClass); 
       } else {
           elem.addClass(errorClass);
       }
     },    
     unhighlight: function (element, errorClass, validClass) {
         var elem = $(element);
         if (elem.hasClass("select2-hidden-accessible")) {
              $("#select2-" + elem.attr("id") + "-container").parent().removeClass(errorClass);
         } else {
             elem.removeClass(errorClass);
         }
     },
     errorPlacement: function(error, element) {
       var elem = $(element);
       if (elem.hasClass("select2-hidden-accessible")) {
           element = $("#select2-" + elem.attr("id") + "-container").parent(); 
           error.insertAfter(element);
       } else {
           error.insertAfter(element);
       }
     }
   });

$('select').select2({}).on("change", function (e) {
  $(this).valid()
});
</script>

I have detailed this in a blog post: http://chadkuehn.com/jquery-validate-select2/我在博客文章中对此进行了详细说明: http : //chadkuehn.com/jquery-validate-select2/

When you place a Select2 on a SELECT tag it hides the original element.当您将 Select2 放在 SELECT 标签上时,它会隐藏原始元素。 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.在此处查看演示

Found an answer on the forums @ https://github.com/select2/select2/issues/215 posted by corinnaerin .corinnaerin发布的论坛 @ https://github.com/select2/select2/issues/215上找到了答案。 Worked perfectly for me.非常适合我。 Sample code at http://plnkr.co/edit/4QaSguIiYsJtLpuPF8Rc?p=preview http://plnkr.co/edit/4QaSguIiYsJtLpuPF8Rc?p=preview 上的示例代码

      var $select = $('select').select2({
        placeholder: 'Choose',
        allowClear: true
      });

      /*
       * When you change the value the select via select2, it triggers
       * a 'change' event, but the jquery validation plugin
       * only re-validates on 'blur'
       */
      $select.on('change', function() {
        $(this).trigger('blur');
      });

      $('#myForm').validate({
        ignore: 'input[type=hidden], .select2-input, .select2-focusser'
      });

I've found that getting Select2 to work with jQuery Validate very much depends on the markup used in creating the Select2 control.我发现让 Select2 与 jQuery Validate 一起工作在很大程度上取决于创建 Select2 控件时使用的标记。

For the most practical use of the plugin, you'll probably be using dynamically loaded data (data obtained via web service vs. static <option/> elements in the page).对于插件的最实际使用,您可能会使用动态加载的数据(通过 Web 服务获得的数据与页面中的静态<option/>元素)。 And per their spec , the way to accomplish this is by attaching Select2 to an <input type="hidden"/> element.根据他们的规范,实现这一点的方法是将 Select2 附加到<input type="hidden"/>元素。 However, elements of type="hidden" are not validated by jQuery Validate by default.但是,默认情况下,jQuery Validate 不会验证 type="hidden" 的元素。

In order to validate hidden elements using jQuery Validate, one must tinker with the ignore property in jQuery Validate's configuration object.为了使用 jQuery Validate 验证隐藏元素,必须修改 jQuery Validate 配置对象中的ignore属性。 See the ignore option in their spec .请参阅其规范中ignore选项。 Try initializing the ignore value as null to get the validation to trigger.尝试将ignore值初始化为null以触​​发验证。

just add a line in your validation function.只需在验证函数中添加一行。

$('#_form_id').validate({

       ignore: 'input[type=hidden]',
            rules: {
                //Rules
            },
            messages: {
               //messages
            },
}

check out my code.看看我的代码。 I solve my problem by using those codes... few(css,jquery) codes only我通过使用这些代码解决了我的问题......只有几个(css,jquery)代码

 $(document).ready(function() { //form validations--------------------------------------------------------- $('#sample').validate({ ignore: [], errorClass: "error", errorElement: "span" }); $("#receiver_name").select2({ placeholder: "Receiver Name" }); $("#receiver_name").select2().change(function() { $(this).valid(); }); });
 .error .select2-choice.select2-default, .error .select2-choices { color: #a94442; border-color: #a94442; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); } .error:focus, .error .select2-choice.select2-defaultLfocus, .error .select2-choicesLfocus { border-color: #843534; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; } .select2-container .select2-choices .select2-search-field input, .select2-container .select2-choice, .select2-container .select2-choices, .error { border-radius: 1px; }
 <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2-bootstrap.css" rel="stylesheet" /> </head> <body> <form id='sample'> <select class="form-control" name="receiver_name[]" id="receiver_name" multiple required> <option value="1">1</option> <option value="2">2</option> </select> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script> </body> </html>

This doesn't work in Bootstrap Validator() because the validator includes all the inputs in the form.这在 Bootstrap Validator() 中不起作用,因为验证器包含表单中的所有输入。 This means it will validate the input search field of the select2 plugin.这意味着它将验证 select2 插件的输入搜索字段。 which will interfere with the multiselect validation这会干扰多选验证

To fix this simply go to the validator.js Add the select2 input search class .select2-search__field to the ignore list:要解决这个问题,只需转到 validator.js 将 select2 输入搜索类.select2-search__field 添加到忽略列表:

Validator.INPUT_SELECTOR = ':input:not([type="submit"], button, .select2-search__field):enabled:visible'

When you create a custom rule, you also must properly declare it.创建自定义规则时,还必须正确声明它。 Since your custom rule depends on an argument, then you must pass the argument when declaring the rule由于您的自定义规则取决于一个参数,因此您必须在声明规则时传递该参数

rules: {
   country: {
       required: true,
       requiredcountry: "your argument here"  // <- declare the custom rule
   }
}
$("select.select2-me").each(function(index, el) {

    if ($(this).is("[data-rule-required]") && 
    $(this).attr("data-rule-required") == "true") {
        $(this).on('select2-close', function(e) {
            $(this).valid()
        });
    }
});

work for me.为我工作。

You can check this link: https://github.com/rkeshmir/select2-validation Here you can find the simplest way to validate select2 components.您可以查看此链接: https : //github.com/rkeshmir/select2-validation在这里您可以找到验证 select2 组件的最简单方法。 The idea id trigger validation for all <select> items in DOM on their change event.想法 id 触发对 DOM 中所有<select>项目的更改事件的验证。 Also I have added required CSS rules to highlight error and success states of input.我还添加了必需的 CSS 规则来突出显示输入的错误和成功状态。

To validate 'select2' inputs you first must tell jquery validate to consider hidden elements:要验证“select2”输入,您首先必须告诉 jquery validate 考虑隐藏元素:

$.validator.setDefaults({ 
ignore: [],
});

This is custom highlight / unhighlight that i use for pointing select2 and tagit errors with jquery validate:这是自定义突出显示/取消突出显示,我用于通过 jquery 验证指向 select2 和 tagit 错误:

$("#someform").validate({
        rules: {
            nazwa: {
                required: true
            },
            ilosc_w_opakowaniu: {
                required: "#czy_opakowanie_zbiorcze:checked"
            }
        },
        messages: {
            nazwa: "Musisz wypełnić pole [Nazwa]",
            ilosc_w_opakowaniu: "Musisz podać ilość produktu w opakowaniu zbiorczym",
        },

        highlight: function( element, errorClass, validClass ) {
            if ( element.type === "radio" ) {
                this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
            } else {
                $( element ).addClass( errorClass ).removeClass( validClass );
            }

            // select2
            if( $(element).hasClass('select2-hidden-accessible') ){
                dzik = $(element).next('span.select2');
                if(dzik)
                    dzik.addClass( errorClass ).removeClass( validClass );
            }

            // tagit
            dzik2 = $(element).parent().find('ul.tagit') 
            if( dzik2.length == 1 )
                dzik2.addClass( errorClass ).removeClass( validClass );

        },
        unhighlight: function( element, errorClass, validClass ) {
            if ( element.type === "radio" ) {
                this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
            } else {
                $( element ).removeClass( errorClass ).addClass( validClass );
            }

            // select2
            if( $(element).hasClass('select2-hidden-accessible') ){
                dzik = $(element).next('span.select2');
                if(dzik)
                    dzik.removeClass( errorClass ).addClass( validClass );
            }

            // tagit
            dzik2 = $(element).parent().find('ul.tagit') 
            if( dzik2.length == 1 )
                dzik2.removeClass( errorClass ).addClass( validClass );
        }
     });

And some CSS:还有一些CSS:

/** select2 error hightight **/
.select2.error .select2-selection--single{
    border-color:red !important;
    color:red !important;
}

/** tagit error highlight **/
.tagit.error{
   border-color:red !important;
   color:red !important;
}

I solved the problem, the solution is to modify the highlight, unhighlight and above all errorPlacement methods for each instance of validate.我解决了这个问题,解决方案是修改每个validate实例的highlight、unhighlight以及最重要的errorPlacement方法。 However, in order not to modify each file, I put the modifications in the file jquery.validate.js不过为了不修改每个文件,我把修改的内容放在文件jquery.validate.js中

highlight: function( element, errorClass, validClass ) {
        if ( element.type === "radio" ) {
            this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
        } else {
            var elem = $(element);
            if (elem.attr('readonly') == 'readonly') {
                if (elem.hasClass("input-group-addon")) {
                   $("#" + elem.attr("id")).parent().addClass(errorClass);
                } else {
                    $( element ).addClass( errorClass ).removeClass( validClass );
                }
            } else {
                if (elem.hasClass("select2-hidden-accessible")) {
                   $("#select2-" + elem.attr("id") + "-container").parent().addClass(errorClass);
                } else {
                    $( element ).addClass( errorClass ).removeClass( validClass );
                }
            }
        }
    },
    unhighlight: function( element, errorClass, validClass ) {
        if ( element.type === "radio" ) {
            this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
        } else {
            var elem = $(element);
            if (elem.attr('readonly') == 'readonly') {
                if (elem.hasClass("input-group-addon")) {
                   $("#" + elem.attr("id")).parent().removeClass(errorClass);
                } else {
                    $( element ).addClass( errorClass ).removeClass( validClass );
                }
            } else {
                if (elem.hasClass("select2-hidden-accessible")) {
                    $("#select2-" + elem.attr("id") + "-container").parent().removeClass(errorClass);
                } else {
                    $( element ).removeClass( errorClass ).addClass( validClass );
                }
            }
        }
    },
    errorPlacement: function(error, element) {
        var elem = $(element);
        if (elem.attr('readonly') == 'readonly') {
            element = $("#" + elem.attr("id")).parent();
            error.insertAfter(element);
        } else {
            if (elem.hasClass("select2-hidden-accessible")) {
                element = $("#select2-" + elem.attr("id") + "-container").parent().parent().parent();
                error.insertAfter(element);
            } else {
                error.insertAfter(element);
            }
        }
    }

According to the error placement logic of jQuery validator, you may use the markup like below.根据 jQuery 验证器的错误放置逻辑,您可以使用如下标记。

<div class="input-group col-sm-12">
  <select class="form-control select2" id="ELEMENT ID" name="ELEMENT NAME">
  </select>
</div>

It will place the error block below the select2 box and make the error block visible.它将错误块放置在 select2 框下方并使错误块可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM