Validating dynamic fields with Jquery.validate ()

0

I'm having trouble validating fields in a PivotTable using the jquery.validate () plugin where input are sequential.

JS

$("#addLinha").on("click", function () { 
   // ADD QTD DE LINHAS INFORMADAS NO INPUP
   var n_prod = $("#n_prod").val(); 
   for ( var i = 0 ; i < n_prod ; i++ ) {
     contador++;
     var newRow = $("<tr>");
     var cols = "";

     cols += '<td class="contador" >' + contador + '</td>';
     cols += '<td><label text-align="center"><input class="produto" type="text" name="produto' + contador + '" /></label></td>';
     cols += '<td><label text-align="center"><input class="qtd spinner"     type="text" name="qtd' + contador + '"    onkeyup="somenteNumeros(this);"   /></label></td>';
     cols += '<td><label text-align="center"><input class="preco"   type="text" name="preco' + contador + '"  align="center" /></label></td>';
     cols += '<td class="col-md-2 total">R$ 0.00</td>';
     cols += '<td><a class="deleteLinha"> Excluir </a></td>';

     newRow.append(cols);

     $("#products-table").append(newRow);
  }
});

I tried to create validation rules as follows, but it did not work as I expected:

$('#produto').validate({
   errorElement: 'div',
   errorClass: 'help-block',
   focusInvalid: true,
      rules: {
         for ( i = 1 ; i <= $('#hidden_linha').val() ; i++ ) {
            produto+i:{ required: true, maxlength: 100, minlength: 3 } 
         }
      }
});
    
asked by anonymous 06.03.2018 / 14:52

1 answer

2

Consider validating the form as a whole and treat the elements you want to validate in the rules, so you apply .validate() to <form> and not directly to the element.

In your case involving the creation of <input /> dynamically remember that the plugin will only be able to identify the elements to be validated if they already exist, so call $(form).validate(); after the creation of elements.

Another important factor is that you do not need to create the same rule for every <input /> .

The rules by default identifies the elements by the name property but the plugin allows you to create new rules, where you can identify and validate elements of a certain class, for example:

jQuery.validator.addClassRules('produto', {
   required: true
});

Plugin documentation for future reference.

Responding to comment:

Yes, it is possible to customize both the message and its sketching:

//Crio um método com mensagem costumizada
$.validator.addMethod("prodRequired", $.validator.methods.required,"Produto é obrigatório");

//Abaixo defino como será as mensagens de erro.
$("#formulario").validate({
   errorPlacement: function(label, element) {
     label.addClass('arrow');
     label.insertAfter(element);
   },
   wrapper: 'span'
});

Sources:

Example working:

var contador = 0;

//Cria um método com mensagem.
$.validator.addMethod("prodRequired", $.validator.methods.required,
"Produto é obrigatório");

//Regra para a classe produto
jQuery.validator.addClassRules('produto', {
    prodRequired: true
});
    
$("#addLinha").on("click", function () { 
  // ADD QTD DE LINHAS INFORMADAS NO INPUP
  var n_prod = $("#n_prod").val(); 
  for ( var i = 0 ; i < n_prod ; i++ ) {
    contador ++;

    var newRow = $("<tr>");
    var cols = "";

    cols += '<td class="contador" >' + contador + '</td>';
    cols += '<td><label text-align="center"><input class="produto" type="text" name="produto' + contador + '" /></label></td>';
    cols += '<td><label text-align="center"><input class="qtd spinner"     type="text" name="qtd' + contador + '"    onkeyup="somenteNumeros(this);"   /></label></td>';
    cols += '<td><label text-align="center"><input class="preco"   type="text" name="preco' + contador + '"  align="center" /></label></td>';
    cols += '<td class="col-md-2 total">R$ 0.00</td>';
    cols += '<td><a class="deleteLinha"> Excluir </a></td>';

    newRow.append(cols);

    $("#products-table").append(newRow);
  }

  //Abaixo defino como será as mensagens de erro.
  $("#formulario").validate({
    errorPlacement: function(label, element) {
          label.addClass('arrow');
          label.insertAfter(element);
      },
      wrapper: 'span'
  });
  
});
span.arrow {
    margin-left: 6px;
    height:17px;
    background: url('http://i45.tinypic.com/f9ifz6.png') no-repeat left center;
}
label.error {
    height:17px;
    border-top:1px solid #99182c;
    border-right:1px solid #99182c;
    border-bottom:1px solid #99182c;
    margin-left:9px;
    padding:1px 5px 0px 5px;
    font-size:small;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>


<form id="formulario">
  <div>
    <input type="number" id="n_prod" name="n_prod" min="1" value="1" />
    <button type="button" id="addLinha">
      Adicionar Linha
    </button>
  </div>
  <div>
    <table id="products-table">
    </table>
  </div>
  <div>
    <button type="submit" id="enviar" name="enviar">
      Enviar
    </button>
  </div>
</form>
    
06.03.2018 / 16:30