Validate array of inputs in form in Laravel 5.7

前端 未结 6 1413
生来不讨喜
生来不讨喜 2021-01-20 01:59

My form has the same input field multiple times. My form field is as follows:




        
6条回答
  •  长发绾君心
    2021-01-20 02:58

    You can use a custom rule with a closure.

    https://laravel.com/docs/5.7/validation#custom-validation-rules

    To check if an array has all null values check it with array_filter which returns false if they're all null.

    So something like...

      $request->validate([
    
        'items' => [
          // $attribute = 'items', $value = items array, $fail = error message as string
           function($attribute, $value, $fail) {
             if (!array_filter($value)) {
               $fail($attribute.' is empty.');
             } 
           },
         ]
       ]);
    

    This will set the error message: 'items is empty."

提交回复
热议问题