Skip to content Skip to sidebar Skip to footer

Bootstrap Validation On Dynamically Adding Multiple Fields

I am using bootstrap v3.1.1 and I want to validate a form with bootstrap validation but who contains a button to clone 3 fields. With cloning everything works nice, but I can't val

Solution 1:

if you insert the method addField in your input loop, it should work. I also suggest to save your first row as a template.

var template = $('#line_1').clone();
var options = {
    fields: {
        'firstField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 1'
                }
            }
        },
        'secondField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 2'
                }
            }
        },
        'thirdField[]': {
            validators: {
                notEmpty: {
                    message: 'Enter a value 3'
                }
            }
        }
    }
};
$('#myForm').bootstrapValidator(options);

$('#cloneButton').click(function () {
    var rowId = $('.row').length + 1;
    var validator = $('#myForm').data('bootstrapValidator');
    var klon = template.clone();          
    klon.attr('id', 'line_' + rowId)
        .insertAfter($('.row').last())
        .find('input')
        .each(function () {
            $(this).attr('id', $(this).attr('id').replace(/_(\d*)$/, "_"+rowId));
            validator.addField($(this));
        })                   
});

FIDDLE

Solution 2:

This Answer not exactly for this question but if someone want to add different field dynamically then they can use this.

$('#myForm').formValidation('addField', 'fourthField[]', {
            validators: {
                    notEmpty: {
                        message: 'Enter a value 4'
                    }
                },
});

Syntax : $("#form_name").formValidation("addField",'no of the field',{validation});

Post a Comment for "Bootstrap Validation On Dynamically Adding Multiple Fields"