Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

php - Laravel validate at least one item in a form array

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

<input type="number" name="items[{{ $sku }}]" min="0" />
<input type="number" name="items[{{ $sku }}]" min="0" />
<input type="number" name="items[{{ $sku }}]" min="0" />

I would like to validate that there is at least one of those input fields that has a value.

I tried the following in my OrderCreateRequest, yet the test is passing:

return [
    'items' => 'required|array|min:1'
];

Am I missing something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

AppProvidersValidatorServiceProvider::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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...