My Laravel后端接收一个JSON转换的Javascript数组,并将其解码为以下php数组:
dd($cart(编辑的密钥已更改
array:4 [▼
"personcount" => 2
"person1" => array:2 [▼
"Customer" => array:2 [▶]
"Items" => array:5 [▼
"key1" => 0
"key2" => 0
"key3" => 0
"key4" => 0
"key5" => 1
]
]
"person2" => array:2 [▼
"Customer" => array:2 [▶]
"Items" => array:5 [▶]
]
]
我创建了一个Filter中间件,它应该验证给定的数组,并在失败时重定向回。
Filter.phpEDITED添加了新的(无效的(验证规则方法
$cart = json_decode($request->input('cart'), true);
$validation_rules = [];
$TotalItemCount = 0;
for ($i = 1; $i <= $person_count; $i++) {
foreach ($cart[$i]["Items"] as $Item => $ItemCount) {
$TotalItemCount += $ItemCount;
}
$validation_rules += [
"person$i.Customer.FirstName" => "required|string|min:2|max:255",
"person$i.Customer.LastName" => "required|string|min:2|max:255",
"person$i.Items.*" => "required|numeric",
"person$i.Items" => ['required', 'array',
Rule::in(["Key1", "Items"]),
],
];
}
$validated_input = Validator::make($cart, $validation_rules);
验证器似乎忽略了$i.Items验证规则。我甚至把size:5改成了size:6,因为给定的Item Array总是只包含5个元素,所以必须100%触发错误。
此外,我尝试验证数组密钥:
"$i.Items" => "required|array:key1,key2,key3"
它也根本没有开火。我希望所有的钥匙都是必需的。firstName/Lastname规则适用。
我很乐意接受你的建议。
经过大量研究和努力,我找到了解决方案:
对于在Laravel 8+中拼命搜索高级数组验证示例的每个人:
- 步骤:ALWAY使用数组,而不是对象。为此:
public function fCreateArrayFromObject($Object) {
$toArray = function ($x) use (&$toArray) {
return is_scalar($x)
? $x
: array_map($toArray, (array)$x);
};
return $toArray($Object);
}
- 步骤:我将用我的例子向您展示它是如何轻松完成的:
<blockquote\>我的数组($cart(:
array:3 [▼
"user1" => array:2 [▼
"Items" => array:5 [▼
"blue" => 0
"grey" => 1
"brown" => 1
"look" => 0
"black" => 0
]
"User" => array:2 [▼
"LastName" => "alice"
"FirstName" => "Bobby"
]
]
"user2" => ......
]
我的规则:
$person_count = 2; // Up to 5
$validation_rules = [];
for ($i = 1; $i <= $person_count; $i++) {
$validation_rules += [
"user$i" => "array:Items,Customer|size:2|distinct",
"user$i.user.FirstName" => "required|string|min:2|max:255",
"user$i.user.LastName" => "required|string|min:2|max:255",
"user$i.Items.*" => "required|numeric|min:0",
"user$i.Items" => "required|array:blue,grey,brown,look,black|size:5|distinct",
];
}
操作:
$validated_input = Validator::make((array)$cart, $validation_rules);
我不太确定,为什么make方法不能将没有(array(的$cart数组解释为数组,但它是有效的。目标:
- 验证整个购物车:必须将每个人包含为一个正好有2个元素的数组(最多5个数组(有效
- 验证每个人本身:必须包含用户和项目数组工作
- 验证用户数组:必须包含2到255个字符之间的名字和姓氏,因为字符串有效
- 验证Items数组:大小必须恰好为5,必须包含所有给定的键工作
- 验证Items数组的键值:它们必须是数字的,并且至少有0个有效
显然,一切都必须存在:";"必需";
标签:Laravel阵列验证,Laravel嵌套阵列验证
而不是
"required|array:key1,key2,key3"
你会做一些类似的事情
'required|in:' . $this->array() . ''