javascript JQuery 验证:如何在多个选择中检查项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3916669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:41:28  来源:igfitidea点击:

JQuery validation : How to check items in multiple select

javascriptjqueryvalidationselect

提问by slok

I have a form using JQuery validation plugin.

我有一个使用 JQuery 验证插件的表单。

<label>
    <input name="Distribution[]" type="checkbox" id="dist_europe" class="required minlength:1" value="Europe" />  Europe 
</label>

<select name="Europe[]" size="5" multiple id="Europe">
   <option value='Albania'>Albania</option>
   <option value='Andorra'>Andorra</option>
   <option value='Austria'>Austria</option>
</select>

I need to do 'conditional' validation. eg. If checkbox is selected, make sure at least one item in 'select option is selected'.

我需要进行“有条件”验证。例如。如果选择了复选框,请确保至少选择了“选择选项”中的一项。

 $(document).ready(function(){
     $("#commentForm").validate({
      rules: {
              Europe: {
                required: "#dist_europe:checked",
                minlength: 1
              }  
      },
      messages: {
        Europe: "Please select at least 1 country"
      }
     }
})

The issue I am facing now is :

我现在面临的问题是:

  1. I am able to detect that the checkbox is selected.
  2. However, I am not able to check the 'select' array, Europe[]
  3. If I remove the array, and name it Europe, I will be able to detect that at least one item is selected. But, doing that will mean the backend PHP script will not be able to process the multiple select in the array.
  1. 我能够检测到复选框被选中。
  2. 但是,我无法检查“选择”数组 Europe[]
  3. 如果我删除数组并将其命名为 Europe,我将能够检测到至少选择了一项。但是,这样做意味着后端 PHP 脚本将无法处理数组中的多选。

How do I work around this? Thanks

我该如何解决这个问题?谢谢

回答by Nick Craver

When using a name like name="Europe[]", you'll need to use a string for your identifier (the identifier is the name, not the idof the element) in rulesand messages, like this:

使用类似 的名称时name="Europe[]",您需要在and 中使用字符串作为标识符(标识符是名称,而不是元素的id),如下所示:rulesmessages

$(document).ready(function(){
     $("#commentForm").validate({
      rules: {
        'Europe[]': {
                required: "#dist_europe:checked",
                minlength: 1
              }  
      },
      messages: {
        'Europe[]': "Please select at least 1 country"
      },
     debug: true
    });
});

You can test it out here.

你可以在这里测试一下