I am using the jQuery Validate Plugin that is available on the official jQuery website to validade my forms. Everything was going just fine until I have to pass rules, not based on a field name, but on class or id. I can’t manage to do that.
This an example of how I am passing rules to the field with name="comment".
This is my jQuery code
$("#comForm").validate({
rules: {
comment: {
required: true,
minlength: 5,
maxlength: 500
}
}
});
This is my form
<form id="comForm" action="#" method="post" >
<textarea rows="4" name="comment" placeholder="What do you think?" class="input-xxlarge" id="defaultform"></textarea></br>
<textarea rows="4" name="othercomment" placeholder="What do you think?" class="input-xxlarge" id="defaultform"></textarea></br>
<input type="submit" value="Rate!" class="btn btn-primary">
</form>
Let’s just say I want to pass the rules to every field with the default form id or to all fields with input-xxlarge class. Is that possible?
Yes it’s possible, but you really should not use duplicate
id‘s… it’s invalid HTML and it will lead to JavaScript issues. Useclassif you need duplicates.Use the built-in
rules()method to add rules and assign them byclass. See documentation.Then use jQuery’s
.each()method to to apply rules to all matching elements using that sameclass.HTML:
jQuery:
Working DEMO
Also, similar to this question:
jQuery Validate set rule using wildcard to find target fields