Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery validate plugin - can't validate classes

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?

like image 253
flyagaricus Avatar asked Apr 21 '11 18:04

flyagaricus


2 Answers

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/

like image 151
Andrew Whitaker Avatar answered Nov 17 '22 16:11

Andrew Whitaker


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

like image 45
Aaron Hill Avatar answered Nov 17 '22 15:11

Aaron Hill