Laravel 4 验证 - 嵌套索引数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17974231/
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 08:12:54  来源:igfitidea点击:

Laravel 4 Validation - Nested Indexed Arrays?

phplaravel

提问by Captain flapHyman

I have an array of various things...

我有各种各样的东西......

$foo = [];
$foo['stuff']['item'][0]['title' => 'flying_lotus'];
$foo['stuff']['item'][1]['title' => 'various_cheeses'];
$foo['stuff']['item'][2]['title' => 'the_career_of_vanilla_ice'];
$foo['stuff']['item'][3]['title' => 'welsh_cats'];

How would I validate the 'title' key, using the Validator method in Laravel 4?

我将如何使用 Laravel 4 中的 Validator 方法验证“title”键?

Here's what I have so far...

这是我到目前为止...

$validator = Validator::make($foo, ['stuff.item.???.title' => 'required']);

I'm totally flummoxed by the indexed array. Any help would be great .

我完全被索引数组搞糊涂了。任何帮助都会很棒。

回答by Aken Roberts

The following answer is for Laravel <= 5.1. Laravel 5.2 introduced built-in array validation.

以下答案适用于 Laravel <= 5.1。Laravel 5.2 引入了内置数组验证



At this time, the Validator class isn't meant to iterate over array data. While it can traverse through a nested array to find a specific value, it expects that value to be a single (typically string) value.

此时,Validator 类不打算迭代数组数据。虽然它可以遍历嵌套数组以查找特定值,但它期望该值是单个(通常是string)值。

The way I see it, you have a few options:

在我看来,你有几个选择:

1: Create rules with the array key in the field name.

1:使用字段名称中的数组键创建规则。

Basically essentially what you're doing already, except you'd need to figure out exactly how many values your ['stuff']['item']array has. I did something like this with good results:

基本上你已经在做什么,除了你需要弄清楚你的['stuff']['item']数组有多少个值。我做了这样的事情,结果很好:

$data = [
    'stuff' => [
        'item'  => [
            ['title' => 'flying_lotus'],
            ['title' => 'various_cheeses'],
            ['title' => ''],
            ['title' => 'welsh_cats'],
        ]
    ]
];

$rules = [];

for ($i = 0, $c = count($data['stuff']['item']); $i < $c; $i++)
{
    $rules["stuff.item.{$i}.title"] = 'required';
}

$v = Validator::make($data, $rules);

var_dump($v->passes());

2: Create a custom validation method.

2:创建自定义验证方法。

This will allow you to create your own rule, where you can expect an array value and iterate it over as necessary.

这将允许您创建自己的规则,您可以在其中期望数组值并根据需要对其进行迭代。

This method has its caveats, in that A) you won't have specific value error messages, since it'll error for the entire array (such as if you pass stuff.itemas the value to check), and B) you'll need to check all of your array's possible values in your custom function (I'm assuming you'll have more than just titleto validate).

此方法有其警告,因为 A) 您不会有特定的值错误消息,因为它会在整个数组中出错(例如,如果您stuff.item作为要检查的值传递),并且 B) 您需要检查您的自定义函数中所有数组的可能值(我假设您将不仅仅title需要验证)。

You can create the validation method by using the Validator::extend()or by fully extending the class somewhere else.

您可以通过使用Validator::extend()或 通过在其他地方完全扩展类来创建验证方法。

3: Extend the Validator class and replace/parent the rules in question to accept arrays.

3:扩展 Validator 类并替换/父有问题的规则以接受数组。

Create your own extended Validator class, and either implement custom rules, or rename existing ones, enabling those rules to accept an array value if one happens along. This has some similar caveats to the #2 custom rule option, but may be the "best practice" if you intend on validating iterated arrays often.

创建您自己的扩展 Validator 类,并实现自定义规则或重命名现有规则,使这些规则在发生时接受数组值。这与 #2 自定义规则选项有一些类似的警告,但如果您打算经常验证迭代数组,这可能是“最佳实践”。

回答by patricksayshi

As @Cryode said, Laravel doesn't currently offer this functionality out of the box. I created a class extending the default Laravel Validator to add an iterate($attribute, $rules, $messages)method.

正如@Cryode 所说,Laravel 目前没有提供这种开箱即用的功能。我创建了一个扩展默认 Laravel 验证器的类来添加一个iterate($attribute, $rules, $messages)方法。

It can also iterate recursively through arrays so that (for example) if you have any number of "books", each of which may have any number of "citations", this will still work, which @Cryode's example does not do, so this is a little more robust.

它还可以通过数组递归迭代,以便(例如)如果您有任意数量的“书籍”,每本书可能有任意数量的“引用”,这仍然有效,@Cryode 的示例不这样做,所以这更健壮一点。

https://github.com/penoonan/laravel-iterable-validator

https://github.com/penoonan/laravel-iterable-validator

回答by rob

In addition to @Cryode answer, and for my laravel 5 issue.

除了@Cryode 的回答,还有我的 Laravel 5 问题。

my form has an database id index. so my form fields have the index

我的表单有一个数据库 ID 索引。所以我的表单字段有索引

$foo['stuff']['item'][8]['title' => 'flying_lotus'];
$foo['stuff']['item'][12]['title' => 'various_cheeses'];
$foo['stuff']['item'][23]['title' => 'the_career_of_vanilla_ice'];

i used foreach to reach my goal

我用 foreach 来达到我的目标

foreach($request->input()['stuff']['items'] as $key => $value){
    $rules["stuff.items.{$key}.title"] = 'required';
}

and the custom error messages

和自定义错误消息

foreach($request->input()['stuff']['items'] as $key => $value){
    $messages["stuff.items.{$key}.title.required"] = 'Each Title is required...';
}

and validate

并验证

Validator::make($request->input(), $rules, $messages);