2015-10-27 204 views
5

我想打一個laravel驗證該驗證未命名的數組(0,1,2,3)即是一個數組Laravel驗證使用通配符

所以我的數組類似於

裏面裏面的字段
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 * 
    ]); 

回答

5

Laravel 5.2

在問題的語法現在支持

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

Laravel 5.1

首先創建所有的其他規則的驗證。使用物品的array規則

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

然後使用Validator each方法一組規則適用於每一個項目的項目數組英寸

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

這會自動將這些規則你...

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

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

+1

太棒了!不知道這一點。一定要包含在文檔中! –

+1

看起來像新的laravel(5.2)添加了我的建議:D – AlhasanIQ

+0

@AlhasanIQ yep,並且很高興能夠在一個地方設置所有規則。我會更新我的回答 – andrewtweber

0

你可以簡單地做這樣的事情:

$rules = []; 
    for($i = 0; $i < 10; $i++) { 
     $rules["items.$i.id"] = "required"; 
    } 
    $validator = \Validator::make($request->all(), $rules); 
+0

這工作,但Laravel已經具有完成同樣的事情的'each'方法,何必再 - 發生輪子? – andrewtweber

+0

好嗎? http://laravel.com/docs/5.1/validation#available-validation-rules我無法在文檔中找到它。 –

+0

並非一切都記錄在案。它在源代碼中,請參閱我的回答中的鏈接 – andrewtweber