validate dynamic field with validate

Asked

Viewed 653 times

0

I’m trying to do a validation for a dynamic field with validate, but it only validates once. The dynamically added fields are not being validated follows below:

$(document).ready(function() {
  $(".data").mask("99/99/9999");

  var i = 1;
  $('a#adicionar').click(function() {
    i++;

    $('#dynamic_field').append('<tr id="row' + i + '"><td>Inicio:</td><td><input name="inicio[]" id="inicio' + i + '" type="text" value="" class="form-control data" /></td><td>Término:</td><td><input name="termino[]" id="termino' + i + '"type="text" value="" class="form-control data" /></td><td><a name="remove" id="' + i + '" class="btn btn-danger btn_remove"><i class="fa fa-times-circle">-</i></a></td></tr>');
    $(".data").mask("99/99/9999");
    $("#inicio" + i + "").focus();

  });

  $(document).on('click', 'a.btn_remove', function() {
    var button_id = $(this).attr("id");
    $('#row' + button_id + '').remove();
  });

  $("#teste").validate({

    rules: {

      'inicio[]': {
        required: true,
      date: true

      },
      'termino[]': {
        required: true,
      date: true

      }
    },
    messages: {
      'inicio[]': "* Informe uma data",
      'termino[]': "* Informe uma data",

    },
    highlight: function(element) {
      $(element).closest('.form-group').removeClass('has-success').addClass('has-error')
      $(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
    },
    unhighlight: function(element) {
      $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
      $(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
    },
    //errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
      if (element.parent('.input-group').length) {
        error.insertAfter(element.parent());
      } else {
        error.insertAfter(element);
      }
    }
  });
});
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"></script>
<form id="teste">
  <div class="col-sm-12">
    <table class="table" width="100%" id="dynamic_field">
      <tr>
        <td>Inicio:</td>
        <td>
          <input name="inicio[]" id="inicio" type="text" value="" class="form-control data" />
        </td>
        <td>Término:</td>
        <td>
          <input name="termino[]" id="termino" type="text" value="" class="form-control data" />
        </td>
        <td></td>
      </tr>
    </table>
    <a id="adicionar" class="btn btn-success" title="Adicionar data de início e término"><i class="fa fa-plus-circle">+</i></a>
  </div>
  <button type="submit" id="btn_passo2" class="btn btn-primary next-step">Salvar</button>
</form>

I put tbm in jsfiddle for better understanding https://jsfiddle.net/opeta/p4jbc49f/

from now on I appreciate any help.

  • If you click Ctrl+M you will see that you have a Jsfiddle-like feature right here on the site.

  • @whatever the problem is?

  • Wouldn’t it be better if you used an HTML5 date input? Because there would already dispense with any validations, since it would already limit the value of the field to only valid dates.

  • It depends. If you want a more customized validation I recommend using jQuery Validate. If you do not want a custom validation you can use the date type of Html5 itself, just add the required attribute. Ex: https://jsfiddle.net/p4jbc49f/1/

  • @Newtech the problem is that it validates only the first field when I add it does not validate. I am using jquery validate.

  • Mark your answer as the right one.

Show 1 more comment

1 answer

0


got the solution and I come here to share to anyone who has a similar problem can solve:

i was using jquery.validate.min.js and I started using the full version jquery.validate.js inside it I searched for checkForm and replaced the entire function with this one:

checkForm: function() {
        this.prepareForm();
        for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
            if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
                for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
                    this.check( this.findByName( elements[i].name )[cnt] );
                }
            } else {
                this.check( elements[i] );
            }
        }
        return this.valid();
    },

and replace that

var i = 1;
  $('a#adicionar').click(function() {
    i++;

    $('#dynamic_field').append('<tr id="row' + i + '"><td>Inicio:</td><td><input name="inicio[]" id="inicio' + i + '" type="text" value="" class="form-control data" /></td><td>Término:</td><td><input name="termino[]" id="termino' + i + '"type="text" value="" class="form-control data" /></td><td><a name="remove" id="' + i + '" class="btn btn-danger btn_remove"><i class="fa fa-times-circle">-</i></a></td></tr>');
    $(".data").mask("99/99/9999");
    $("#inicio" + i + "").focus();

  });

therefore:

var i = 1;
  $('a#adicionar').click(function() {
    i++;

    $('#dynamic_field').append('<tr id="row' + i + '"><td>Inicio:</td><td><input name="inicio[]" id="inicio' + i + '" type="text" value="" class="form-control data" /></td><td>Término:</td><td><input name="termino[]" id="termino' + i + '"type="text" value="" class="form-control data" /></td><td><a name="remove" id="' + i + '" class="btn btn-danger btn_remove"><i class="fa fa-times-circle">-</i></a></td></tr>');
    $(".data").mask("99/99/9999");
    $("#inicio" + i + "").focus();

$('[name^="inicio"], [name^="termino"]').each(function () {
            $(this).rules("add", {
                required: true,
                  messages: {
            required: "* Informe a data"
          }

            });


            });

  });

source: https://stackoverflow.com/questions/10783358/validating-array-file-input

Browser other questions tagged

You are not signed in. Login or sign up in order to post.