Validate dynamic field jquery

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" />

Leave a Comment