Validate array of inputs in form in Laravel 5.7

前端 未结 6 1399
生来不讨喜
生来不讨喜 2021-01-20 01:59

My form has the same input field multiple times. My form field is as follows:




        
相关标签:
6条回答
  • 2021-01-20 02:51

    Just Do it normally as you always do:

     $validator = Validator::make($request->all(),[
        'items' => 'required'
      ]);
    
    0 讨论(0)
  • 2021-01-20 02:54

    You can check it like this:

    $validator = Validator::make($request->all(), [
        "items"    => "required|array|min:1",
        "items.*"  => "required|string|distinct|min:1",
    ]);
    

    In the example above:

    • "items" must be an array with at least 1 elements.
    • Values in the "items" array must be distinct (unique) strings, at least 1 characters long.
    0 讨论(0)
  • 2021-01-20 02:54

    Knowing you are using the latest version of Laravel, I really suggest looking into Form Request feature. That way you can decouple validation from your controller keeping it much cleaner.

    Anyways as the answer above me suggested, it should be sufficient for you to go with:

    'items' => 'required|array'
    
    0 讨论(0)
  • 2021-01-20 02:56

    You should try this:

    $validator = $request->validate([
        "items"    => "required|array|min:3",
        "items.*"  => "required|string|distinct|min:3",
    ]);
    
    0 讨论(0)
  • 2021-01-20 02:58

    You can use a custom rule with a closure.

    https://laravel.com/docs/5.7/validation#custom-validation-rules

    To check if an array has all null values check it with array_filter which returns false if they're all null.

    So something like...

      $request->validate([
    
        'items' => [
          // $attribute = 'items', $value = items array, $fail = error message as string
           function($attribute, $value, $fail) {
             if (!array_filter($value)) {
               $fail($attribute.' is empty.');
             } 
           },
         ]
       ]);
    

    This will set the error message: 'items is empty."

    0 讨论(0)
  • 2021-01-20 03:05

    In fact, it's enough to use:

    $validator = Validator::make($request->all(),[
            'items' => 'required|array'
        ]);
    

    The changes made:

    • use items instead of items.* - you want to set rule of general items, if you use items.* it means you apply rule to each sent element of array separately
    • removed size:1 because it would mean you want to have exactly one element sent (and you want at least one). You don't need it at all because you have required rule. You can read documentation for required rule and you can read in there that empty array would case that required rule will fail, so this required rule for array makes that array should have at least 1 element, so you don't need min:1 or size:1 at all
    0 讨论(0)
提交回复
热议问题