I'm using the jQuery validation plugin trying to add rules based on data- attributes. I'm adding min/maxlength rules based on data-minlength or data-maxlength. Here's some sample HTML:
<form>
<input name="input1" data-maxlength="5" data-minlength="3" required>
<input name="input2" data-maxlength="5" required>
<input name="input3" data-minlength="3" required>
<button>Submit</button>
</form>
I'm doing this to add the rules and it's working fine:
$('input[data-minlength]').each(function(){
if ($(this).data('minlength')) {
$(this).rules("add", {
minlength: $(this).data('minlength')
});
}
});
$('input[data-maxlength]').each(function(){
if ($(this).data('maxlength')) {
$(this).rules("add", {
maxlength: $(this).data('maxlength')
});
}
});
But I wanted to shorten it up, so I tried this and it's not working:
['minlength', 'maxlength'].forEach(function(item){
$('input[data-'+item+']').each(function(){
if ($(this).data(item)) {
// alert(item) shows the correct rule name
$(this).rules("add", {
// Next line fails, but hardcoding a rule name works
item: $(this).data(item)
});
}
});
});
The error is because $.validator.methods[method] is undefined. Somehow it's getting the wrong method name passed to it, even though alert(item) tells me the rule name is correct.
Does anyone have any idea why, or have an alternate solution I can use to shorten up the repetitive, working code above?