对动态表单元素使用 jQuery 验证插件

Using jQuery Validation Plugin with dynamic form elements

我有一个包含多个表单的页面,每个表单可以包含任意数量的元素,这些元素在其名称中具有共同的根。我正在尝试使用 this answer 来验证提交的表单,但我在 jquery.validate.js 上收到 TypeError: a.data(...) is undefined 错误。我的代码如下。

    var valForm = function(kit_id) {
        $('input[name^="kit_desc_"]').each(function() {
            $(this).rules("add", {
                required: true,
                messages: {
                    required: "Please enter a description"
                }
            });
        });

        $("#frm_" + kit_id).validate({
            errorElement: "div",
            errorPlacement: function(error, element) {
                $("#error_modal").html(error);
            }
        });

        if (! $("#frm_" + kit_id).valid()) {
            // a dialog box will appear listing the errors.
            $("#error_modal").dialog();
        }
    };

单击 link 时调用该函数。

<a href="javascript:;" onclick="valForm(1);" class="button136">Save</a>

有什么建议吗?

我认为您必须先在表单上调用 .validate(),然后才能在该表单的输入上调用 .rules()。您还应该仅在您提交的表单中的输入上调用 .rules()

var valForm = function(kit_id) {
    var form = $("#frm_" + kit_id);
    form.validate({
        errorElement: "div",
        errorPlacement: function(error, element) {
            $("#error_modal").html(error);
        }
    });

    form.find('input[name^="kit_desc_"]').each(function() {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "Please enter a description"
            }
        });
    });

    if (! form.valid()) {
        // a dialog box will appear listing the errors.
        $("#error_modal").dialog();
    }
};