带有通配符的 Laravel 验证器

Laravel validator with a wildcard(带有通配符的 Laravel 验证器)
本文介绍了带有通配符的 Laravel 验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想制作一个 Laravel 验证器来验证数组内的未命名数组 ( 0,1,2,3 ) 内的字段

i want to make a laravel validator that validates the the fields inside an un-named array ( 0,1,2,3 ) that is inside an array

所以我的数组就像

array [ //the form data
  "items" => array:2 [ //the main array i want to validate
    0 => array:2 [ // the inner array that i want to validate its data
      "id" => "1"
      "quantity" => "1000"
     ]
    1 => array:2 [
     "id" => "1"
     "quantity" => "1000"
     ]
  // other fields of the form,
  ]

]

所以我想要的是像

  $validator = Validator::make($request->all(), [
     'items.*.id' => 'required' //notice the star *
  ]);

推荐答案

Laravel 5.2

现在支持问题中的语法

http://laravel.com/docs/master/validation#validating-arrays

Laravel 5.1

首先使用您的所有其他规则创建验证器.对项目使用 array 规则

First create the validator with all of your other rules. Use the array rule for items

$validator = Validator::make($request->all(), [
    'items' => 'array',
    // your other rules here
]);

然后使用 Validator each 方法将一组规则应用于 items 数组中的每个项目.

Then use the Validator each method to apply a set of rules to every item in the items array.

$validator->each('items', [
    'id'       => 'required',
    'quantity' => 'min:0', 
]);

这将自动为您设置这些规则...

This will automatically set these rules for you...

items.*.id       => required
items.*.quantity => min:0

https://github.com/laravel/framework/blob/5.1/src/Illuminate/Validation/Validator.php#L261

这篇关于带有通配符的 Laravel 验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

In PHP how can you clear a WSDL cache?(在 PHP 中如何清除 WSDL 缓存?)
failed to open stream: HTTP wrapper does not support writeable connections(无法打开流:HTTP 包装器不支持可写连接)
Stop caching for PHP 5.5.3 in MAMP(在 MAMP 中停止缓存 PHP 5.5.3)
Caching HTTP responses when they are dynamically created by PHP(缓存由 PHP 动态创建的 HTTP 响应)
Memcached vs APC which one should I choose?(Memcached 与 APC 我应该选择哪一个?)
What is causing quot;Unable to allocate memory for poolquot; in PHP?(是什么导致“无法为池分配内存?在 PHP 中?)