Laravel validate at least one item in a form array

后端 未结 8 1026
借酒劲吻你
借酒劲吻你 2020-12-30 11:12

I have a form with a series of numbers in an array:




        
相关标签:
8条回答
  • 2020-12-30 12:08
    $valid = Validator($request->all(), [
        'type' => 'required|string|in:city,region,country',
    ]);
    
    if ($valid->fails()) return response()->json($valid->errors(), 400);
    
    0 讨论(0)
  • 2020-12-30 12:12

    I think you need a custom validation rule like the following because min is not for the elements of the array.

    Validator::extend('check_array', function ($attribute, $value, $parameters, $validator) {
         return count(array_filter($value, function($var) use ($parameters) { return ( $var && $var >= $parameters[0]); }));
    });
    

    You can create ValidatorServiceProvider and you can add these lines to boot method of ValidatorServiceProvider. Then you need to add Provider to your providers array in config/app.php.

    App\Providers\ValidatorServiceProvider::class,
    

    Or you just add them top of the action of your controller.

    At the end you can use it like this in your validation rules.

    'items' => 'check_array:1',
    

    Note: if I understand you correctly it works.

    0 讨论(0)
提交回复
热议问题