0

Good afternoon, I came across the following question.

I'm using the jQuery Validation plugin to validate my form v1.13.0 client side.

Is working just fine.

But the problem I can not solve it is:

I have a field name "product []", which is an array. I may have one or I may have 20 products in this array.

Here is my Code:

data_emissao:   {required: true},
forma_pagamento:    {required: true},
produto[]:  {required: true}, // tried this with no sucess

Anyone ever run into this problem?

Sparky
  • 98,165
  • 25
  • 199
  • 285

2 Answers2

2

Two issues...

1) If your field name contains brackets, dots or other special characters, then you must enclose the name in quotes.

"produto[]":  {
    required: true
}

2) However, unless the input contains this exact name, name="produto[]", then it will not work as you cannot declare an array within the rules option of .validate(). The rules option only accepts a list of individual field names.


Two possible solutions...

1) You could use the .rules() method as follows. Using a jQuery "starts with" selector to select the entire array and a jQuery .each() to apply the .rules('add') method to every field in this group.

$('[name^="produto"]').each(function() {  // select elements using "starts with" selector
    $(this).rules('add', {
        required: true,
        // other rules
    });
});

2) However, if the only rule is required, then you would not need to declare it using any JavaScript at all. You could just use the required HTML5 attribute instead, and the jQuery Validate plugin will still pick it up.

<input type="text" name="produto[0]" required="required" />
<input type="text" name="produto[1]" required="required" />
<input type="text" name="produto[2]" required="required" />
<input type="text" name="produto[3]" required="required" />
<input type="text" name="produto[4]" required="required" />
Sparky
  • 98,165
  • 25
  • 199
  • 285
-1

If you are using produto as an array, you must specify its index or it wouldn't work as expected. Try using produto[0] to indicated that you require at least one value on your array.

Matheus Godoy
  • 72
  • 1
  • 5