問題描述
我想制作一個(gè) Laravel 驗(yàn)證器來驗(yàn)證數(shù)組內(nèi)的未命名數(shù)組 ( 0,1,2,3 ) 內(nèi)的字段
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
所以我的數(shù)組就像
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
現(xiàn)在支持問題中的語法
http://laravel.com/docs/master/validation#validating-arrays
Laravel 5.1
首先使用您的所有其他規(guī)則創(chuàng)建驗(yàn)證器.對(duì)項(xiàng)目使用 array
規(guī)則
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
方法將一組規(guī)則應(yīng)用于 items 數(shù)組中的每個(gè)項(xiàng)目.
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',
]);
這將自動(dòng)為您設(shè)置這些規(guī)則...
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
這篇關(guān)于帶有通配符的 Laravel 驗(yàn)證器的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!