I am using jQuery validation plugin trying to add rules based on data- attributes. I add min / maxlength rules based on data-minlength or data-maxlength . Here are some examples of 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 do this to add rules, and it works 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, so I tried this and did not work:
['minlength', 'maxlength'].forEach(function(item){ $('input[data-'+item+']').each(function(){ if ($(this).data(item)) {
The error is due to the fact that $.validator.methods[method] is undefined. Somehow he received the wrong method name passed to him, although alert(item) tells me the correct name.
Can anyone understand why, or have an alternative solution that I can use to reduce the repetitive working code above?
Demo: http://jsfiddle.net/kaVKe/1/
source share