Tim*_*ktu 7 php validation laravel laravel-5
我的应用程序允许用户同时上传多个图像文件,但我无法弄清楚如何验证图像数组.
$input = Request::all();
$rules = array(
...
'image' => 'required|image'
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::to('venue-add')
->withErrors($messages);
} else { ...
Run Code Online (Sandbox Code Playgroud)
'image'如果我将验证规则更改为:如果是数组,则此验证将失败:
$rules = array(
...
'image' => 'required|array'
);
Run Code Online (Sandbox Code Playgroud)
验证将通过,但阵列内部的图像尚未验证.
这个答案使用关键字each作为验证规则的前缀,但是这是在laravel 4.2和Laravel 5中它似乎不起作用.
我一直试图在每个图像上单独迭代数组和验证,但是有没有内置函数来为我做这个?
Bad*_*eeq 18
这适合我
$rules = array(
...
'image' => 'required',
'image.*' => 'image|mimes:jpg,jpeg'
);Run Code Online (Sandbox Code Playgroud)
在那另一个做它.
我使用了一种类似于 Jeemusu 推荐的技术,并在初始验证后确保图像数组存在,使用第二个验证器遍历数组,确保数组中的每个项目实际上都是一个图像。这是代码:
$input = Request::all();
$rules = array(
'name' => 'required',
'location' => 'required',
'capacity' => 'required',
'description' => 'required',
'image' => 'required|array'
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::to('venue-add')
->withErrors($messages);
}
$imageRules = array(
'image' => 'image|max:2000'
);
foreach($input['image'] as $image)
{
$image = array('image' => $image);
$imageValidator = Validator::make($image, $imageRules);
if ($imageValidator->fails()) {
$messages = $imageValidator->messages();
return Redirect::to('venue-add')
->withErrors($messages);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
同意@Badmus Taifeeq 答案,但它将接受具有任何值的图像字段,而不检查字段是否为数组。你需要添加一些小东西
请参阅下面的代码进行正确的验证
$rules = array(
'image' => 'required|array',
'image.*' => 'image|mimes:jpg,jpeg'
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6302 次 |
| 最近记录: |