Validate dynamic field jquery

▼魔方 西西 提交于 2019-12-17 16:54:43

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/26022085/validate-dynamic-field-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!