使用 jquery 验证插件验证选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19751898/
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-08-27 00:33:08  来源:igfitidea点击:

validate select with jquery validation plugin

jqueryjquery-validate

提问by s.k.paul

I have a html select with a default value -1.

我有一个默认值为 -1 的 html 选择。

  <select id="BusinessDistrictId">
       <option value="-1">Select one...</option>
       //other options...
  </select>

I would like to force the users to select any option other than -1 value. My jquery validation rules-

我想强制用户选择 -1 值以外的任何选项。我的 jquery 验证规则-

  rules: {
         BusinessDistrictId: { required: true , min:0}
        }

But it's not working. Any suggestion?

但它不起作用。有什么建议吗?

回答by Sparky

If you want to validate this element with the jQuery Validate plugin, there are two problems with its markup...

如果你想用 jQuery Validate 插件验证这个元素,它的标记有两个问题......

<select id="BusinessDistrictId">
    <option value="-1">Select one...</option>
    //other options...
</select>

1) As per the requirements of the jQuery Validate plugin, every element must have a unique nameattribute. When rules are declared within .validate(), they are identified by their name. However, no matter how rules are declared, every element must still have a unique nameattribute because that's how the plugin keeps track of the form elements.

1) 根据 jQuery Validate 插件的要求,每个元素都必须有一个唯一的name属性。当规则在其中声明时.validate(),它们由它们的name. 然而,无论规则如何声明,每个元素仍然必须有一个唯一的name属性,因为这是插件跟踪表单元素的方式。

2) Your min: 0rule is only a workaround for a broken requiredrule. In order to use required: trueon a <select>element, you must have the value=""attribute on the first <option>element; so in your case, the requiredrule will always be ignored.And since you have the min: 0rule, you are getting a similar validation result that requires an item to be selected. Even with the value=""attribute on the first option, having both the requiredand minrules on a selectelement makes no logical sense.

2) 您的min: 0规则只是对违反required规则的一种解决方法。为了required: true<select>元素上使用,您必须value=""在第一个<option>元素上拥有该属性;所以 在你的情况下,required规则将始终被忽略。并且由于您拥有min: 0规则,您将获得类似的验证结果,需要选择一个项目。即使value=""在 first 上有属性,在元素上option同时使用requiredmin规则select也没有逻辑意义。

Here is the correct code...

这是正确的代码...

HTML:

HTML:

<select id="BusinessDistrictId" name="BusinessDistrictId">
    <option value="">Select one...</option> <!-- first option contains value="" -->
    //other options...
</select>

jQuery:

jQuery

rules: {
    BusinessDistrictId: {  // <-- this is the name attribute
        required: true
    }
},

DEMO: http://jsfiddle.net/y82dV/

演示:http: //jsfiddle.net/y82dV/

回答by s.k.paul

adding name="BusinessDistrictId" solved my issue.

添加 name="BusinessDistrictId" 解决了我的问题。