Jquery: Bootstrap Form Validation Library Does Not Work on Dynamically Added Items

advertisements

I am using bootstap validator library for form validation.

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

Sometime my form is dynamically added (based on some conditions made by the user) and at that time validation does not work.

When the form is dynamically added the validation rules are not working. I know jquery.on event can be used to solve this issue, but how can I use it in my case?


jQuery.on may not help you in this context, since you are using a plugin.

Looking at the website for BootrapValidator, it looks like it has been superseded by FormValidation.

Putting that aside, it looks like your best bet would be to create a function that binds the validator, and call that function when you add form elements dynamically.

For example:

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