【发布时间】:2016-12-21 13:44:50
【问题描述】:
好的,这个问题很搞笑,但我需要解决它:
我正在使用 Laravel 5.2 并制作表单来上传图片。我有这个规则:
public static $rules = array(
'picture ' => 'required|mimes:jpg,jpeg,png',
'description' => 'required'
);
The description validation is ok, but when validating the picture, the 'required' attribute seems to work vice versa - when a file (picture) is selected, then it fails to validate (error: 'The picture field is required' ),当没有文件时,验证成功。
这是来自我的控制器的代码:
Log::info('Validating store picture request');
$validator = Validator::make(Input::all(), Picture::$rules);
$validator->after(function ($validator) {
Log::info('After method');
// check for validity of the file
if (!Input::file('picture')->isValid()) {
Log::info('Picture is not valid');
$validator->errors()->add('picture', 'Picture is not valid');
}
});
if ($validator->fails()) {
Log::info('Validation failed, returning back');
$messages = $validator->messages();
return back()
->withErrors($validator)
->withInput(Input::except('picture'));
}
Log::info('Validation succeed, continuing');
编辑:我以这种方式记录了 Validator 类:
protected function validateRequired($attribute, $value)
{
Log::info('Just logging required validation');
Log::info('is_null: '.is_null($value));
if (is_null($value)) {
Log::info('Reason: is_null');
return false;
} elseif (is_string($value) && trim($value) === '') {
return false;
} elseif ((is_array($value) || $value instanceof Countable) && count($value) < 1) {
return false;
} elseif ($value instanceof File) {
Log::info('File, getpath '.$value->getPath());
return (string) $value->getPath() != '';
}
Log::info('Continuing');
return true;
}
这就是我提交表单时得到的结果带有文件:
[2016-08-15 12:18:27] local.INFO: Validating store picture request
[2016-08-15 12:18:27] local.INFO: Just logging required validation
[2016-08-15 12:18:27] local.INFO: is_null: 1
[2016-08-15 12:18:27] local.INFO: Reason: is_null
[2016-08-15 12:18:27] local.INFO: Just logging required validation
[2016-08-15 12:18:27] local.INFO: is_null: 1
[2016-08-15 12:18:27] local.INFO: Reason: is_null
[2016-08-15 12:18:27] local.INFO: After method
[2016-08-15 12:18:27] local.INFO: Validation failed, returning back
编辑:当没有文件时,我得到相同的日志输出,所以现在它的行为方式相同..我不知道为什么每次请求执行两次:/
【问题讨论】:
-
太奇怪了。 上的 enctype 属性怎么样
-
有'multipart/form-data' - 图片的上传和存储工作正常(当缺少验证时)
-
我之前也遇到过同样的问题。您可以尝试其他验证规则。比如“image”或“mimetypes:image/jpeg,image/png”
-
使用
required|file|mimes:jpg,jpeg,png -
你确定这是 Laravel 5.2 吗?
标签: php validation laravel file-upload laravel-5.2