Jquery validation. Validate array of arrays

149 Views Asked by At

I am using jquery validation to validate a form. It works fine when it comes to validate simple variables or even and array variable but here is the thing: I need to validate an array of arrays.

My code looks something like this:

<input type="text" name="phones[0][prefix]" />
<input type="text" name="phones[0][number]" />
<input type="text" name="phones[1][prefix]" />
<input type="text" name="phones[1][number]" />

The number of phones fields are unlimited so I might have one or more.

The validation that I need to apply consists in checking that both prefix and number are not empty for each phone.

Does anybody have and idea of how to make the validation for this case. Anything I read so far has helped me.

Thanks in advance.

1

There are 1 best solutions below

0
Hackerman On

You can set custom rules, based on a selector; for example, this selector $('input[name*=prefix]') gets all the inputs that contains prefix in the input name:

 //custom rules
$('input[name*=prefix]').each(function(i,elem){
    $(elem).rules("add", { 
    required:true,  
    minlength:3,
    number: true,
    messages: {
      required: "Required custom input",
      minlength: jQuery.validator.format("Please, at least {0} characters are necessary"),
      number: "Only numbers custom again"
    }
  });    
}) 

You can see it working here: http://jsfiddle.net/pmv16q8t/