laravel 中的多数组验证
Multiple array validation in laravel
我有 3 种类型的数据要验证
- 分组数据
- 单条数据
- 单组数据合并
此验证适用于单个数据
$validator = Validator::make($request->all(), [
'tests.*.finding' => 'required',//works for single test
]);
以上数据示例
["tests"=>
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
]
并且此验证适用于组中的数据
$validator = Validator::make($request->all(), [
'tests.*.*.finding' => 'required',//works for group
]);
以上数据示例
["tests"=>
[
"A" =>[
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
],
"B" =>[
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
]
]
]
如何验证单个数据和组中数据的组合
组合数据样本
["tests"=>
[
"A" =>[
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
]
],
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
]
请帮我解决这个问题,因为第一种情况总是给第二种情况带来错误,反之亦然。
您可以按照以下代码修复验证数据。
$customFieldValidation = ["test_id" => 'required|numeric',
"test_two.id" => 'required|numeric',
]);
$this->setRules ( $customFieldValidation );
$customeAttributes = [
"test_three.*.id" => 'Test Three ' // custom message
];
$this->setCustomAttributes ($customeAttributes);
$this->_validate ();
希望对你有所帮助
这是解决方案,Laravel 提供了 sometimes
规则来管理元素的存在,然后只继续检查下一个规则。
所以最终的验证规则是。
$validator = Validator::make($request->all(), [
'tests.*.*.finding' => 'sometimes|required',//works for group
'tests.*.finding' => 'sometimes|required',//works for single test
]);
相关文档:https://laravel.com/docs/5.4/validation#conditionally-adding-rules
我有 3 种类型的数据要验证
- 分组数据
- 单条数据
- 单组数据合并
此验证适用于单个数据
$validator = Validator::make($request->all(), [
'tests.*.finding' => 'required',//works for single test
]);
以上数据示例
["tests"=>
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
]
并且此验证适用于组中的数据
$validator = Validator::make($request->all(), [
'tests.*.*.finding' => 'required',//works for group
]);
以上数据示例
["tests"=>
[
"A" =>[
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
],
"B" =>[
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
]
]
]
如何验证单个数据和组中数据的组合
组合数据样本
["tests"=>
[
"A" =>[
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
]
],
[
0 => ["finding"=>""]
],
[
1 => ["finding"=>""]
]
]
请帮我解决这个问题,因为第一种情况总是给第二种情况带来错误,反之亦然。
您可以按照以下代码修复验证数据。
$customFieldValidation = ["test_id" => 'required|numeric',
"test_two.id" => 'required|numeric',
]);
$this->setRules ( $customFieldValidation );
$customeAttributes = [
"test_three.*.id" => 'Test Three ' // custom message
];
$this->setCustomAttributes ($customeAttributes);
$this->_validate ();
希望对你有所帮助
这是解决方案,Laravel 提供了 sometimes
规则来管理元素的存在,然后只继续检查下一个规则。
所以最终的验证规则是。
$validator = Validator::make($request->all(), [
'tests.*.*.finding' => 'sometimes|required',//works for group
'tests.*.finding' => 'sometimes|required',//works for single test
]);
相关文档:https://laravel.com/docs/5.4/validation#conditionally-adding-rules