I was trying to wire up the jQuery Validator plugin to work with data attributes instead of direct attributes (examples: data-minlength instead of minlength, data-equalTo instead of equalTo) so that my markup would validate as valid HTML5. Everything was working great until I got to data-equalTo. I ended up having to use data-equals instead and put a special condition in my code:
$("#form").validate();
['minlength', 'maxlength', 'range', 'min', 'max', 'equals' /* 'equalTo' no worky! */].forEach(function (item) {
$('input[data-' + item + ']').each(function () {
if ($(this).data(item)) {
var rule = {};
if (item == 'equals') /* special condition because 'equalTo' never makes it into this if block */
rule['equalTo'] = $(this).data(item);
else
rule[item] = $(this).data(item);
$(this).rules("add", rule);
}
});
});
The problem seemed to be with the $('input[data-' + item + ']') selector. For whatever reason it was not selecting for data-equalTo. Is it reserved, or unable to be selected via jQuery for some reason?
Now working based on Yoshi’s feedback:
['minlength', 'maxlength', 'range', 'min', 'max', 'equalTo'].forEach(function (item) {
$('input[data-' + item + ']').each(function () {
var lowerItem = item.toLowerCase();
if ($(this).data(lowerItem)) {
var rule = {};
rule[item] = $(this).data(lowerItem);
$(this).rules("add", rule);
}
});
});
Using jquery, you’ll have to access the data-attributes in lowercase. In your case:
and if that is unwanted, try
attrthough, you’ll not get the auto-parsing from jquery in that case.
demo: http://jsfiddle.net/BS6wy/1/