0

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.

5
  • You can use something like $('input[name*=phones]'), or console.log($('input[name*=prefix]')) Commented Jul 5, 2018 at 20:49
  • I am using jquery validation to validate my fields and I need to set a rule to validate these particular fields. I don't see how to do it based on your answer. Could you please explain a little bit more? Commented Jul 5, 2018 at 21:22
  • Let me create a little example Commented Jul 5, 2018 at 21:24
  • Take a look at this example: jsfiddle.net/pmv16q8t Commented Jul 5, 2018 at 21:32
  • I added custom rules based on the $('input[name*=prefix]') selector, with custom messages :) Commented Jul 5, 2018 at 21:32

1 Answer 1

0

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.