Laravel validator with a wildcard

前端 未结 2 1137
-上瘾入骨i
-上瘾入骨i 2020-12-06 17:54

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

so my array is like

ar         


        
相关标签:
2条回答
  • 2020-12-06 18:38

    You could simply do something like that:

        $rules = [];
        for($i = 0; $i < 10; $i++) {
            $rules["items.$i.id"] = "required";
        }
        $validator = \Validator::make($request->all(), $rules);
    
    0 讨论(0)
  • 2020-12-06 18:55

    Laravel 5.2

    The syntax in the question is now supported

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

    Laravel 5.1

    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
    ]);
    

    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

    0 讨论(0)
提交回复
热议问题