Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

php - Validate array of inputs in form in Laravel 5.7

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

<input type='text' name='items[]'>
<input type='text' name='items[]'>
<input type='text' name='items[]'>

And request contains ($request['items'):

array:1 [▼
  "items" => array:3 [▼
    0 => "item one"
    1 => "item two"
    2 => "item three"
  ]
]

I want atleast one of the items to be filled. My current validation in the controller is

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

It does not work. I tried with combination of size, required, nullable. Nothing works.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...