用 "Validation Rules" 验证 "Runtime JSON array"

Validate "Runtime JSON array" with "Validation Rules"

我们知道有几个插件可以使用 jQuery 在 HTML 表单上执行验证。

我们正在使用 jQuery 数据表,使用数据表编辑器进行内联编辑。

https://editor.datatables.net/examples/api/clientValidation.html

问题是每次提交一行时,每行中的几个字段都是可编辑的,我们真的不想继续编写 "if-else" 条件来验证所有可能的可编辑列。

当用户编辑单元格时,我们得到的是一个JSON名称-值数组(当前行数据),例如这种格式,

var rowData = { 
              fld_name1: "value1",
              fld_name2: "value2",
              fld_name3: "value3"
              fld_name4: "value4"
              fld_name5: "value5"
           }

想检查我们是否可以将此数组提供给任何验证规则数组,例如 jQuery 验证插件使用的格式,https://jqueryvalidation.org/files/demo/

rules: {
            fld_name1: "required",
            fld_name2: "required",
            fld_name3: {
                required: true,
                minlength: 2
            },
            fld_name4: {
                required: true,
                minlength: 5
            },

            fld_name5: "required"
        },

并检查当前 "rowData" 是否符合 "rules" 数组中定义的规则。

这里"rowData"数组是动态数组,为数据表中的每一行创建了1个单独的实例。

另外 HTML 表单元素(文本字段)由 jQuery 数据表编辑器动态生成。因此,没有选项可以在 jQuery 验证插件上设置表单类型初始化。

我擅长使用任何可以提供此运行时数组验证功能的 jQuery 验证。

When user edits cell, what we get is a JSON name-value array (current Row data), for example in this format .... Wanted to check if we can feed this array to any validations rules array for e.g format used by JQuery Validation Plugin

您不能 "dynamically" 向 rules 对象中输入任何内容。由于 .validate() 在页面加载时调用 一次 来初始化插件,因此无法再次调用...它被忽略了。

Also HTML FORM Element (Text Field) is generated dynamically by jQuery Datatables Editor. So don't have option to setup form type init on jQuery Validation plugin.

虽然您无法使用 .validate() 初始化动态字段,但开发人员提供了一个名为 .rules() 的方法,您可以调用该方法从任何表单输入元素动态分配、更新或删除规则 随时。因此,您必须解析 JSON 数组并根据需要应用 .rules()...

$('[name="fld_name1"]').rules('add', {
    required: true,
    minlength: 2
});

演示:http://jsfiddle.net/ejc1dq8g/

您可以一次应用于多个字段,只要您将选择器附加到 .each()

$('[name^="fld_"]').each(function() {
    $(this).rules('add', {
        required: true,
        minlength: 2
    });
});

或者,您可以简单地在任何表单输入元素上使用 HTML5 validation attributes,并且 jQuery 验证插件将自动拾取和使用这些元素,即使是动态的创建元素。

<input name="fld_name1" required="required" minlength="2" ....

演示 2:http://jsfiddle.net/84zv61n4/


编辑:

引用 :

"There is no wrapping form as such on which we can call .validate()"

如果是这种情况,您绝对不能在没有 <form></form> 容器的情况下使用 jQuery 验证插件。没有解决方法。我希望你能在 OP 中提到这个关键细节,因为它会节省时间和精力。

仅供参考,对于正在寻找运行时 JSON 命名数组验证解决方案的人,以下库解决了这个问题,https://validatejs.org/