我有一个表单,用户必须定义要保存的项目数,当您提交表单并将其解析为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."]
}
}
我怎样才能做到这一点?
答案 0 :(得分:2)
一种方法是编写自定义验证器(您可以将它放在AppServiceProvider @ boot方法中)。像(未测试/伪代码)的东西:
@ManyToOne(fetch = FetchType.EAGER)
private User user;
https://laravel.com/docs/5.5/validation#custom-validation-rules
答案 1 :(得分:-1)
size rule接受一个数值,然后将其与输入[1]的大小进行比较,它不接受字段引用。
如果您想与另一个字段的值进行比较,您需要自己传递该字段值,例如:
$aValidations = [
"numItems" => "required|int|max:10",
"items" => "required|array|size:" . $data->get('numItems'),
]
注意:假设您已经解码了json,然后创建了一个集合。
e.g:
$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]对于一个字符串,它比较字符数,对于一个整数,它按原样比较值,对于一个数组,它比较顶级元素的数量,对于一个文件,它比较文件大小。