Laravel 验证表单数组中的至少一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45758449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:30:59  来源:igfitidea点击:

Laravel validate at least one item in a form array

phplaravelvalidation

提问by Miguel Stevens

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:

我在OrderCreateRequest 中尝试了以下内容,但测试通过了:

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

Am I missing something?

我错过了什么吗?

采纳答案by Hakan SONMEZ

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

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

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.

您可以创建 ValidatorServiceProvider,并将这些行添加到 ValidatorServiceProvider 的引导方法中。然后你需要将 Provider 添加到 config/app.php 中的 providers 数组中。

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.

注意:如果我理解正确,它会起作用。

回答by Jakhongir

In addition ot Hakan SONMEZ's answer, to check if at least one array element is set, the Ruleobject can be used. For example create rule class and name it ArrayAtLeastOneRequired().

除了 Hakan SONMEZ 的回答,要检查是否至少设置了一个数组元素,可以使用Rule对象。例如,创建规则类并将其命名为 ArrayAtLeastOneRequired()。

To create new rule class run console command:

要创建新的规则类,请运行控制台命令:

php artisan make:rule ArrayAtLeastOneRequired

Then in created class edit method passes():

然后在创建的类中编辑方法pass():

public function passes($attribute, $value)
    {
        foreach ($value as $arrayElement) {
            if (isset($arrayElement)) {
                return true;
            }
        }

        return false;
    }

Use this rule to check if at least one element of array is not null:

使用此规则检查数组中是否至少有一个元素不为空:

Validator::make($request->all(), [
  'array.*' => [new ArrayAtLeastOneRequired()],
 ]);

回答by Umer

If you are using this in your controller file then I guess it should be

如果您在控制器文件中使用它,那么我想它应该是

$this->validate($request, [
    'items' => 'required|min:1'
]);

or this one

或者这个

$validator = Validator::make($request->all(), [
    "items.*" => 'required|min:1',
]);

you can refer How to validate array in Laravel?to this as well.

你可以参考如何在 Laravel 中验证数组?对此也是如此。

回答by Haritsinh Gohil

The accepted answer is ok, and it is working fine, but if you don't want to create function and other stuff then the another workaround which i have used is

接受的答案是可以的,并且工作正常,但是如果您不想创建函数和其他东西,那么我使用的另一种解决方法是

that you can directly state the element of array as items.0and make that input required, it will not care about other inputs but it will make first input required, it is not usable in all the cases but in my case it is useful.

您可以直接将数组元素声明为items.0并要求输入,它不会关心其他输入,但它会要求第一个输入,它不是在所有情况下都可用,但在我的情况下它很有用。

in your OrderCreateRequest:

在您的OrderCreateRequest

public function rules()
{
   return [
       "items.0" => "required",
   ];
}

And if your items are not dynamic and not in very large amount then you can use required_without_allas below:

如果您的项目不是动态的并且数量不是很大,那么您可以使用required_without_all如下:

public function rules()
{
   return [
       "items.0" => "required_without_all:items.1,items.2",
       "items.1" => "required_without_all:items.0,items.2",
       "items.2" => "required_without_all:items.0,items.1",
   ];
}

回答by Dmitry Shilin

$valid = Validator($request->all(), [
    'type' => 'required|string|in:city,region,country',
]);

if ($valid->fails()) return response()->json($valid->errors(), 400);

回答by Giorgio Grasso

You can set your rules for array and foreach elements.

您可以为数组和 foreach 元素设置规则。

public function rulez(Request $req) {
        $v = Validator::make($req->all(), [
            'items'   => 'required|array|min:1',
            'items.*' => 'required|integer|between:0,10'

        ]);

        if ($v->fails())
            return $v->errors()->all();
}

First rule say that items must be an array with 1 element at least. Second rule say that each elements of items must be an integer between 0 and 10.

第一条规则说 items 必须是至少有 1 个元素的数组。第二条规则是项目的每个元素必须是 0 到 10 之间的整数。

If the rules seem not to work, try to dump your $req->all().

如果规则似乎不起作用,请尝试转储您的 $req->all()。

dump($req->all());

回答by Kuldeep Mishra

$this->validate($request,[
'item'=>'required|min:1'

]);

回答by Omar

'items'   => 'required|array', // validate that field must be from array type and at least has one value
'items.*' => 'integer' // validate that every element in that array must be from integer type

and you can add any other validation rules for those elements like: 'items.*' => 'integer|min:0|max:100'

您可以为这些元素添加任何其他验证规则,例如: 'items.*' => 'integer|min:0|max:100'