Doubt how to validate compo with product name[], field is an array

Asked

Viewed 319 times

0

I came across the following doubt.

I am using jQuery Validation Plugin v1.13.0 to validate my client side form.

It’s working, all right.

but the problem I can’t solve is I have a field with a name produto[], which is an array that sends several fields with that name. I can send 1 how can I send 20 products.

data_emissao:   {required: true},
forma_pagamento:    {required: true},
produto[]:  {required: true}, // coloquei assim mais sem sucesso.

someone has come across this problem?

  • What problem are you encountering? it does not validate if it has at least 1 product?

  • It does not validate, this product field[], actually if you put product[]: {required: ""}, from the error in this line

1 answer

2


To validate items of type array, place the element name in single quotes in the validation rules, example:

Demo: Jsfiddle

$("#myform").validate({
    rules: {
        'produto[]': {
            required: true
        }
    }
});

EDIT

Suggested implementation using Rules( "add", Rules ):

Demo Jsfiddle

HTML

<form id="myform">
    <label>
        <input type="text" name="produto[1]" class="produto"/>
    </label>
    <label>
        <input type="text" name="produto[2]" class="produto"/>
    </label>    
    <input type="submit" />
</form>

OBS: The names of inputs need to be unique in case produto[1],produto[2] and etc.

jQuery

$(document).ready(function () {
   $('#myform').validate({
        submitHandler: function (form) { 
            alert('formulário validado');
            form.submit();
        }
    });          
    /* faz loop por todos os elementos com classe produto
    * e adiciona nas regras para validação
    */
    $('input.produto').each(function () {
        $(this).rules('add', {
            required: true
        });
    });

});
  • Abfurlan even validates, but validates only the first product field[] the other fields I add later does not validate. these fields are created dynamically.

  • @Claytoneduardomergulhão What type of input you are using?

  • echo '<td><input type="text" name="product[]" id="txtProduto_1" class="form-control input-xlarge"/></td>';

  • @Claytoneduardomergulhão edited with a possible solution

Browser other questions tagged

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