Adding jQuery validation rules based on data attributes in a loop

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)) { // 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 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/

+6
source share
3 answers

This does not work because you are creating an object literal with a new property called item.

how about this?

 ['minlength', 'maxlength'].forEach(function(item){ $('input[data-'+item+']').each(function(){ if ($(this).data(item)) { // alert(item) shows the correct rule name var options = {}; options[item] = $(this).data(item); $(this).rules("add", options); } }); }); 

This creates an options object and adds the property you need.

+6
source

Try:

 ['minlength', 'maxlength'].forEach(function(item){ $('input[data-'+item+']').each(function(){ if ($(this).data(item)) { var rule = {}; rule[item] = $(this).data(item); $(this).rules("add", rule); } }); }); 

Your solution does not work, because in object literature property names will not be interpreted as variables:

 { item: ... // <-- this one } 
+5
source

Why don't you just do

 $('input').each(function(){ var max = $(this).data('maxlength'); var min = $(this).data('minlength') if (min) { $(this).rules("add", { minlength: min }); } if (max) { $(this).rules("add", { maxlength: max }); } }); 

the fiddle is here http://jsfiddle.net/kaVKe/2/ Your code does not work, I think, because you cannot use a variable for the property name

 // Next line fails, item is always interpreted as item, not as maxlength/minlength item: $(this).data(item) 
+3
source

Source: https://habr.com/ru/post/906872/


All Articles