Validation in Laravel 5 in array fields?

Asked

Viewed 706 times

2

Through site collaborators I managed to ask a question Do a custom validation on Laravel 5 on validation in Laravel, where it was possible, validate a field input text only if a Combobox was checked.

Example:

required_if:anotherfield,value

And now another question has arisen, I have several fields name, which is a input text nomes = nome[] (array), then in the above case it does not accept in the validation, since even being empty, he considers existing due to the existence of the array

There’s a way to do it?

  • place an example of input would be <input type="text" name="nome[]"/>??? and all possible information of the doubt. Note that my edition made reference to your first doubt, which was taken, and with mention of a new doubt!

  • 1

    It is as follows: I have several inputs to register several partners of the company, all fields have the name = name[], that is, when I do a get in the name field, it comes as an array of names, according to the number of fields name[] filled in... But when I do the validation by : >required_if: ... It does not work, and even though no name has been filled in, it passes through and does not accuse in validation ... I imagine this happens because when the array of names is passed to validation, Request accuses that it is ok because there is value (which is the array), but it does not check whether the array has value

2 answers

1


Your FormRequest need to know that the name field is a array and the already has a form of validate the field only needs to have the following nomenclature:

nome_do_campo + .*

As their fields are related the two need to follow the nomenclature nome.* and liberar.* in the validation part, already in the form part (<form>) following example below:

<p>
    <input type="checkbox" value="true" name="liberar[]">
    <input type="text" value="" name="nome[]">
</p>
<p>
    <input type="checkbox" value="true" name="liberar[]">
    <input type="text" value="" name="nome[]">
</p>

Also follows an example of FormRequest:

class ExemploRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'nome.*' => 'required_if:liberar.*,true'
        ];
    }

    public function messages()
    {
        return [                
            'nome.required_if' => 'nome é para ser digitado'
        ];
    }
}

Recommending: you should also control the validation with Javascript to send the data practically correct, and these fields are sequential take good care of it.

0

Browser other questions tagged

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