Laravel 5 Multiple Field Validation

I have a field in the view, something like

<div> <input type="text" name="new[0][description]" id="description-new-0"> <input type="text" name="new[0][amount]" id="amount-new-0"> </div> <div> <input type="text" name="new[1][description]" id="description-new-1"> <input type="text" name="new[1][amount]" id="amount-new-1"> </div> 

etc., so you can imagine that this is a dynamic field that is added to the form every time you check the add button or something else.

The question is, how can I VALIDATE these dynamic fields and return the correct error for each field?

Thanks!

Note that this is Laravel 5, but if you have a Laravel 4 solution similar to this, I think (really guess) it will work.

Thanks guys!

+6
source share
1 answer

Create in the folder Requires a validator for this form, for example

 <?php use Illuminate\Foundation\Http\FormRequest; class MultipleRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'description' => 'required|array', ]; if ($this->request->get('description')) { foreach($this->request->get('description') as $key => $val) { $rules['description.'.$key] = 'required|min:7'; //example } } return $rules; } public function messages() { $messages = []; if ($this->request->get('description')) { foreach ($this->request->get('description') as $key => $val) { $messages['description.' . $key . '.min'] = 'Wrong field.'; $messages['description.' . $key . '.required'] = 'This field required.'; } } return $messages; } } 

Additional Information Practical Guide. Validating an array of form fields with Laravel

then in sight the next

 @if (Session::has('_old_input')) @for ($i=0; $i<count(Session::get('_old_input.description')); $i++) <div> @if($errors->any() && Session::get('errors')->getBag('default')->has('description.' . $i)) <p class="">{{Session::get('errors')->getBag('default')->first('description.' . $i)}}</p> @endif <input type="text" name="new[][description]" id="description-new-{{$i}}" value="{{Session::get('_old_input.description.' . $i)}}"> <input type="text" name="new[][amount]" id="amount-new-{{$i}}" value="{{Session::get('_old_input.amount.' . $i)}}"> </div> @endfor @endif 

therefore, you add a block with an error message for each block with inputs. In my example, only the description has been processed, the amount that you can process with a similar description For me, this works and looks enter image description here

UPD: Laravel version 5.2 has array validation, so you can create a validation request, for example:

 public function rules() { return [ 'names.*' => 'required|max:50', 'emails.*' => 'required|max:100', ]; } 

for more details read the DOC

+6
source

Source: https://habr.com/ru/post/987314/


All Articles