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

0

I came across the following doubt.

I'm using jQuery Validation Plugin v1.13.0 to validate my client-side form.

It's working, right.

Plus the problem I can not solve is I have a field named produto[] , which is an array that sends several fields with that name. I can send 1 as I can send 20 products.

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

Has anyone ever encountered this problem?

    
asked by anonymous 24.09.2014 / 18:22

1 answer

2

To validate elements of type array , enclose the name of the element in single quotation marks in the validation rules, for example:

Demo: JSFiddle

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

EDIT

Suggestion of 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>

NOTE: The names of inputs must be unique, in the 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
        });
    });

});
    
24.09.2014 / 19:04