JQuery validate plugin - can't validate classes

做~自己de王妃 提交于 2020-01-10 20:00:12

问题


I'm trying to use the jQuery validate plugin to validate classes instead of ID's. 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. 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? I've tried this:

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

But this does not work at all :(

Any ideas? Anyone?


回答1:


You need to specify a name attribute on each input element for validator to pick it up:

<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/




回答2:


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




回答3:


what about:

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


来源:https://stackoverflow.com/questions/5748346/jquery-validate-plugin-cant-validate-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!