使用 jQuery.validate 动态地在通过 Javascript 生成的表单上输出错误消息

Outputing error messages on a form generated through Javascript dynamically with jQuery.validate

通过Javascript动态生成表单时,验证功能似乎不起作用。验证似乎有效,但未显示错误消息。这有什么原因吗?有什么解决方法吗?

我正在使用它,我意识到当表单被硬编码时这段代码有效,而当代码通过 javascript 生成时无效。

   $('#some-form').validate({
        rules: {
            'feature1': {
                min: 1,
                required: true
            },
            'feature2': {
                min: 1
            },
        },
        messages: {
            'feature1': {
                min: "error1",
                required: "error2"
            },
            'feature2': {
                min: "error3"
            },
        }
});

可能有一些语法错误,因为我没有粘贴代码。

It seems that the validate function doesn't work when the form is dynamically generated through JavaScript.

如果您在 表单创建后调用 .validate() ,它工作得很好。

您不能将 .validate() 方法附加到 DOM 中尚不存在的表单...非常标准的东西。

The validation seems to work, but the error messages aren't displaying.

不可能。如果您没有看到错误消息,则验证插件无法正常工作。

Is there a reason for this and is there any workaround?

如上所述。当 form 是动态生成时,您只能在 创建表单后 立即附加 .validate()

// code that dynamically creates '#some-form' goes here

    $('#content').html('<form id="some-form">...</form>');

// then initialize the plugin on '#some-form' here

    $('#some-form').validate({ // initialize plugin
        ....

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


编辑:

对于动态创建的字段 after after .validate() is called (same as after plugin已初始化),您将使用the .rules() method动态添加和删除规则。