javascriptjquerytwitter-bootstrapformvalidation-plugin

Validate Dynamic input filed with "formvalidation.io"


I am using Plugin Form Validation to validate the form. And this plugin is working awesome.
But i am facing issue in validating dynamically generated inputs.

Below code is used to generate input fields dynamically

$("#countaccmp").change(function() {
  var selVal = $(this).val();
  $("#textboxDiv").html('');
  if(selVal > 0) {
    for(var i = 1; i<= selVal; i++) {
        $("#textboxDiv").append('<input type="text" name="accmp'+i+'" 
        id="accmp'+i+'" class="form-control " />');
    }
  }       
})

I tried validating with plugin as below:

$('#form').formValidation({
       //--------- Plugin Validator Method -----------//
})
.on('change', '[name="countaccmp"]', function(e) {
        //---- Wrote validation here, It works(only on change) but form is getting submitted 
               even after error ----//
       $('.dynDiv').each(function(){
          var input = $(this).children('input');
          var dynField = 
           ($(this).find("input[name^='accmp']").attr('name'));

            if(input.val() == '' || input.val() == undefined){
                alert("Error");
                return false;
            }
 })
 .on('success.form.fv', function(e) {
         //---- Wrote validation here, It works but form is getting 
                submitted even after error ----//
          Same Validation As above
  })

Please let me know solution.


Solution

  • You should add your inputs to the plugin in order to be validated.

    To do so, use the addField method, see bellow:

    $("#countaccmp").change(function () {
        var selVal = $(this).val();
        $("#textboxDiv").html('');
        if (selVal > 0) {
            for (var i = 1; i <= selVal; i++) {
                var input = ''
                    + '<div class="form-group">'
                    + '    <label class="col-sm-3 control-label" for="accmp' + i + '">Accmp ' + i + '</label>'
                    + '    <div class="col-sm-5">'
                    + '        <input type="text" name="accmp' + i + '" id = "accmp' + i + '" class = "form-control " / >'
                    + '    </div>'
                    + '</div>';
                $("#textboxDiv").append(input);
                $('#defaultForm').formValidation('addField', 'accmp' + i, {
                    validators: {
                        // Here, add your field validators.
                    }
                });
            }
        }
    });
    

    Demo:

    References: