简体   繁体   English

JQuery验证插件 - 无法验证类

[英]JQuery validate plugin - can't validate classes

I'm trying to use the jQuery validate plugin to validate classes instead of ID's. 我正在尝试使用jQuery validate插件来验证类而不是ID。 Despite the many threads which seem close to answering this issue - I can't get any of them to work. 尽管许多线程似乎接近于回答这个问题 - 我无法让它们中的任何一个工作。 I simply have a form that has a lot of dynamically generated repeating form fields, so naturally I can't add rules for the ID's because there's no knowing how many of them there will be. 我只是有一个包含大量动态生成的重复表单字段的表单,所以我自然无法为ID添加规则,因为不知道它们中有多少个。 So, instead, I would like to just target the class on the input field. 所以,相反,我想在输入字段上定位类。

<input type="text" id="name1" class="fileName" />
<input type="text" id="name2" class="fileName" />
<input type="text" id="name3" class="fileName" />
<input type="text" id="name4" class="fileName" />

How do I target 'fileName' class? 如何定位'fileName'类? I've tried this: 我试过这个:

$(document).ready(function(){
    $.validator.addClassRules({
        fileName:{
        required: true
    }
    });
    $("#myForm").validate();
});

But this does not work at all :( 但这根本不起作用:(

Any ideas? 有任何想法吗? Anyone? 任何人?

You need to specify a name attribute on each input element for validator to pick it up: 您需要在每个input元素上指定一个name属性,以便验证器将其拾取:

<form action="#">
    <input type="text" id="name1" class="fileName" name="name1" />
    <input type="text" id="name2" class="fileName" name="name2"/>
    <input type="text" id="name3" class="fileName" name="name3"/>
    <input type="text" id="name4" class="fileName" name="name4"/>
</form>

Here's a working example: http://jsfiddle.net/Nbcj9/ 这是一个有效的例子: http//jsfiddle.net/Nbcj9/

According to the docs, this should work: 根据文档,这应该工作:

jQuery.validator.addClassRules('classNameHere', {
  required: true
});

Then you can determine whether the fields are valid by calling: 然后,您可以通过调用以确定字段是否有效:

$('.fileName').valid();

Here's a link to the docs 是文档的链接

关于什么:

$(".fileName").validate();

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

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