Laravel验证表单数组中的至少一项 [英] Laravel validate at least one item in a form array

查看:190
本文介绍了Laravel验证表单数组中的至少一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,其中的数组中包含一系列数字:

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.

我在 OrderCreateRequest 中尝试了以下操作,但测试通过了:

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

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

我想念什么吗?

推荐答案

我认为您需要如下所示的自定义验证规则,因为min不适用于数组的元素.

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]); }));
});

您可以创建ValidatorServiceProvider,并将这些行添加到ValidatorServiceProvider的启动方法中.然后,您需要在config/app.php中将Provider添加到您的provider数组.

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.

这篇关于Laravel验证表单数组中的至少一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆