验证动态字段jQuery [英] Validate dynamic field jquery

查看:88
本文介绍了验证动态字段jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下午好,我遇到了以下问题.

Good afternoon, I came across the following question.

我正在使用jQuery Validation插件来验证表单v1.13.0客户端.

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

工作正常.

但是我无法解决的问题是:

But the problem I can not solve it is:

我有一个字段名称"product []",它是一个数组. 我可能只有一个,或者我可能有20个产品.

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

这是我的代码:

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

有人遇到这个问题吗?

推荐答案

两个问题...

1)如果您的字段名称包含方括号,点或其他特殊字符,则必须将该名称用引号引起来.

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

"produto[]":  {
    required: true
}

2)但是,除非input包含此确切名称name="produto[]",否则它将无法工作,因为您无法在.validate()rules选项中声明数组. rules选项仅接受单个字段名称的列表.

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)您可以按以下方式使用.rules()方法.使用jQuery开始于"选择器选择整个数组,并使用jQuery .each().rules('add')方法应用于该组中的每个字段.

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)但是,如果唯一的规则是required,则根本不需要使用任何JavaScript对其进行声明.您可以只使用required HTML5属性,而jQuery Validate插件仍会选择它.

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

这篇关于验证动态字段jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆