在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:13:46  来源:igfitidea点击:

Validating a JSON array in Laravel

phpjsonlaravellaravel-5laravel-5.2

提问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 orderare unique, and between 1 and 7? I have tried the following:

我如何使用验证器来确保元素在order1 到 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 uniquevalidator 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'
]);