Jquery:启动表单验证库无法处理动态添加的元素


Jquery:Bootstrap form validation library not working on dynamiclly added elements

我正在使用bootstap验证器库进行表单验证。

  //validate when submit button is clicked.
    $('#passenger-form').bootstrapValidator({
     fields: {
       email: {
                    group: '.col-xs-6',
                    validators: {
                        notEmpty: {
                            message: 'Email required'
                        }
                    }
                }
             //rest of the rules here
     }
     });

有时,我的表单是动态添加的(基于用户制定的一些条件),而此时验证不起作用。

动态添加表单时,验证规则不起作用。我知道jquery.on事件可以用来解决这个问题,但在我的情况下如何使用它?

jQuery.on在这种情况下可能对您没有帮助,因为您使用的是插件。

看看BootrapValidator的网站,它似乎已经被FormValidation取代了。

抛开这一点不谈,您的最佳选择似乎是创建一个绑定验证器的函数,并在动态添加表单元素时调用该函数。

例如:

function bindForm() {
    //validate when submit button is clicked.
    $('#passenger-form').bootstrapValidator({
        fields: {
            email: {
                group: '.col-xs-6',
                validators: {
                    notEmpty: {
                        message: 'Email required'
                    }
                }
            }
            //rest of the rules here
        }
     });
}
//call it by default if the form is present
bindForm();
//call it when a user generates an event
function userGeneratedEvent() {
    //do whatever it is that this event is for
    //add the form as described in the question
    bindForm();
}

there is no documentation available in the link you provided, I think the plugin is closed.

好的,这就是想法。由于动态添加的元素是在应用插件后进入DOM的,因此插件对这些元素一无所知。当你添加新的动态元素时,你需要重新应用验证插件。或者更好的方法是不应用插件,但在提交表单时捕获表单提交事件,然后应用插件。这必须更简单,没有更多的开销。