如何在Laravel中验证数组?


104

我尝试在Laravel中验证数组POST:

$validator = Validator::make($request->all(), [
            "name.*" => 'required|distinct|min:3',
            "amount.*" => 'required|integer|min:1',
            "description.*" => "required|string"

        ]);

我发送空的POST,并将其if ($validator->fails()) {}作为False。这意味着验证是正确的,但事实并非如此。

如何在Laravel中验证数组?当我提交表格时input name="name[]"

Answers:


238

星号(*)用于检查数组中的,而不是数组本身。

$validator = Validator::make($request->all(), [
    "names"    => "required|array|min:3",
    "names.*"  => "required|string|distinct|min:3",
]);

在上面的示例中:

  • “名称”必须是包含至少3个元素的数组,
  • “名称”数组中的必须是不同的(唯一)字符串,至少3个字符长。

编辑:由于Laravel 5.5,您可以像这样直接在Request对象上调用validate()方法:

$data = $request->validate([
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);

如果您正在使用,请记住将其放在try catch中$request->validate([...])。如果数据验证失败,将引发异常。
daisura99

如何获取特定字段的错误消息?就像我有2个名称字段,然后是第二个仅包含错误的字段,我该如何实现?
Eem Jee

38

我有这个数组作为来自HTML + Vue.js数据网格/表的请求数据:

[0] => Array
    (
        [item_id] => 1
        [item_no] => 3123
        [size] => 3e
    )
[1] => Array
    (
        [item_id] => 2
        [item_no] => 7688
        [size] => 5b
    )

并使用它来验证哪个可以正常工作:

$this->validate($request, [
    '*.item_id' => 'required|integer',
    '*.item_no' => 'required|integer',
    '*.size'    => 'required|max:191',
]);

2
这正是我需要的东西!
克里斯·

17

编写验证和授权逻辑的推荐方法是将该逻辑放在单独的请求类中。这样,您的控制器代码将保持干净。

您可以通过执行创建请求类php artisan make:request SomeRequest

在每个请求类的rules()方法中,定义您的验证规则:

//SomeRequest.php
public function rules()
{
   return [
    "name"    => [
          'required',
          'array', // input must be an array
          'min:3'  // there must be three members in the array
    ],
    "name.*"  => [
          'required',
          'string',   // input must be of type string
          'distinct', // members of the array must be unique
          'min:3'     // each string must have min 3 chars
    ]
  ];
}

在您的控制器中,编写如下的route函数:

// SomeController.php
public function store(SomeRequest $request) 
{
  // Request is already validated before reaching this point.
  // Your controller logic goes here.
}

public function update(SomeRequest $request)
{
  // It isn't uncommon for the same validation to be required
  // in multiple places in the same controller. A request class
  // can be beneficial in this way.
}

每个请求类都带有验证前和验证后的钩子/方法,可以根据业务逻辑和特殊情况对其进行自定义,以修改请求类的正常行为。

您可以为类似类型的请求(例如webapi)请求创建父请求类,然后在这些父类中封装一些常见的请求逻辑。


6

更复杂的数据,@ Laran和@Nisal Gunawardana的答案的混合

[ 
   {  
       "foodItemsList":[
    {
       "id":7,
       "price":240,
       "quantity":1
                },
               { 
                "id":8,
                "quantity":1
               }],
        "price":340,
        "customer_id":1
   },
   {   
      "foodItemsList":[
    {
       "id":7,
       "quantity":1
    },
    { 
        "id":8,
        "quantity":1
    }],
    "customer_id":2
   }
]

验证规则将是

 return [
            '*.customer_id' => 'required|numeric|exists:customers,id',
            '*.foodItemsList.*.id' => 'required|exists:food_items,id',
            '*.foodItemsList.*.quantity' => 'required|numeric',
        ];

4

您必须遍历输入数组并为每个输入添加规则,如下所述:遍历规则

这是您的一些代码:

$input = Request::all();
$rules = [];

foreach($input['name'] as $key => $val)
{
    $rules['name.'.$key] = 'required|distinct|min:3';
}

$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';

$validator = Validator::make($input, $rules);

//Now check validation:
if ($validator->fails()) 
{ 
  /* do something */ 
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.