gpt4 book ai didi

php - Laravel - 文件需要验证反之亦然

转载 作者:行者123 更新时间:2023-12-04 17:57:34 27 4
gpt4 key购买 nike

好吧,这个问题很搞笑,但我需要解决它:

我正在使用 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' ),当没有文件时,验证成功。

这是来 self 的 Controller 的代码:

    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

编辑:当没有文件时,我得到相同的日志输出,所以现在它的行为方式相同..我不知道为什么每个请求执行两次:/

最佳答案

我刚刚注意到,在您的规则数组中,pictures 键中有一个空格。
我试图检查该空格是否会导致任何错误。是的,它确实没有通过验证。想了想,我认为这应该不会导致错误。

尝试删除那个空格。

public static $rules = array(
'picture' => 'required|mimes:jpg,jpeg,png', //Remove space from 'picture'
'description' => 'required'
);

关于php - Laravel - 文件需要验证反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38953624/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com