Jquery:Bootstrap表单验证库不用于动态添加的元素

时间:2016-03-27 06:23:34

标签: php jquery twitter-bootstrap validation

我正在使用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事件可用于解决此问题,但我如何在我的案例中使用它?

2 个答案:

答案 0 :(得分:1)

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();
}

答案 1 :(得分:1)

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

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

相关问题