Laravel Validator Facade - 根据另一个字段值验证大小

Laravel Validator Facade - Validate size based on another field value

我有一个表单,用户必须在其中定义要保存的项目数,当您提交表单并将其解析为 JSON 时,它看起来像这样:

{
 "numItems": 3,
 "items": [
     "1" : {"A": "Foo", "B:"bar"},
     "2" : {"A": "Foo", "B:"bar"},
     "3" : {"A": "Foo", "B:"bar"},
 ],
}

我想验证 items 中的项目数是否与 numItems 的值匹配。

我试过:

$aValidations = [
    "numItems" => "required|int|max:10",
    "items" => "required|array|size:numItems",
]

但即使项目数量与 numItems 值匹配,我也会得到:

{
    "message": "The given data was invalid.",
    "errors": {
        "items": ["The items must contain numItems items."]
    }
}

我怎样才能做到这一点?

一种方法是编写自定义验证程序(您可以将其放入您的 AppServiceProvider@boot 方法中)。像(不是 tested/pseudocode):

Validator::extend('coolValidatorName', function ($attribute, $value, $parameters, $validator) {
        $data = $validator->getData();
        return $data[$parameters[0]] == count($value)
    });

https://laravel.com/docs/5.5/validation#custom-validation-rules

size rule 接受一个数值,然后将其与输入的大小进行比较[1],它不接受字段引用。

如果您想与从另一个字段中获取的值进行比较,您需要自己传入该字段值,例如:

$aValidations = [
    "numItems" => "required|int|max:10",
    "items" => "required|array|size:" . $data->get('numItems'),
]

注意:假设您已经解码了 json 然后创建了一个集合。

例如:

$json = '{"numItems":4,"items":[{"a":"foo","b":"bar"},{"a":"foo","b":"bar"},{"a":"foo","b":"bar"}]}';

$data = collect((array) json_decode($json));

$aValidations = [
    "numItems" => "required|int|max:10",
    "items" => "required|array|size:" . $data->get('numItems'),
];

[1] 对于字符串,它比较字符数,对于整数,它按原样比较值,对于数组,它比较顶级元素的数量,对于文件,它比较文件大小。