在 Laravel 中验证 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35346329/
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
Validating a JSON array in Laravel
提问by LiquidPL
I have a controller which receives a following POST request:
我有一个控制器,它接收以下 POST 请求:
{
"_token": "csrf token omitted",
"order": [1,2,3,4,5,6,7,8]
}
How can I use validators to ensure that elements in order
are unique, and between 1 and 7? I have tried the following:
我如何使用验证器来确保元素在order
1 到 7 之间是唯一的?我尝试了以下方法:
$this->validate($request, [
'order' => 'required|array',
'order.*' => 'unique|integer|between:1,7'
]);
The first clause is checked, the secound one passes even when the input is invalid.
检查第一个子句,即使输入无效,第二个子句也会通过。
采纳答案by Webinan
The unique
validator keyword is for checking a value's duplicates in database.
该unique
验证关键字是在数据库检查值的重复。
You should use custom validator for such situations.
对于这种情况,您应该使用自定义验证器。
See: https://laravel.com/docs/5.1/validation#custom-validation-rules
请参阅:https: //laravel.com/docs/5.1/validation#custom-validation-rules
回答by Diego Lima
Using distinct rule:
使用不同的规则:
distinct
When working with arrays, the field under validation must not have any duplicate values.
清楚的
使用数组时,验证字段不得有任何重复值。
In your case, it could look like this:
在您的情况下,它可能如下所示:
$this->validate($request, [
'order' => 'required|array',
'order.*' => 'distinct|integer|between:1,7'
]);