我正在尝试像这样验证 Laravel 中的文件类型:
'rules' => ['mimes:pdf,bdoc,asice,png,jpg']
验证适用于
pdf
、png
和 jpg
,但不适用于 bdoc
或 asice
文件(具有这些扩展名的文件不会通过验证)。
我的猜测是,它可能不适用于这些文件类型,因为它们不包含在此处显示的 MIME 类型中:https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf /mime.types
我的假设正确吗?如果是这样,我如何验证这些文件类型?
您需要为特定文件类型创建自定义验证规则。
在此处查看有关创建自定义验证的文档。 https://laravel.com/docs/8.x/validation#custom-validation-rules
更新:添加了一些示例代码。
验证规则
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class AcceptableFileTypesRule implements Rule
{
protected array $acceptableTypes = [];
public function __construct(array $acceptableTypes = [])
{
$this->acceptableTypes = $acceptableTypes;
}
/**
* @param string $attribute
* @param \Illuminate\Http\UploadedFile $value
*
* @return bool
*/
public function passes($attribute, $value): bool
{
return in_array($value->getClientOriginalExtension(), $this->acceptableTypes);
}
public function message(): string
{
// Change the validation error message here
return 'The validation error message.';
}
}
你可以这样使用它
[
'rules' => ['required', new App\Rules\AcceptableFileTypesRule(['pdf,bdoc,asice,png,jpg'])]
]
根据
vendor\laravel\framework\src\Illuminate\Contracts\Validation\Rule.php
的供应商代码,接口 Illuminate\Contracts\Validation\Rule
现已弃用。
namespace Illuminate\Contracts\Validation;
/**
* @deprecated see ValidationRule
*/
interface Rule
{
....
现在建议使用接口
Illuminate\Contracts\Validation\ValidationRule
创建自定义验证规则。因此,要修改@Luigel的答案,Laravel 10中测试的最新实现是:
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule as Rule;
class CustomFileRule implements Rule
{
protected array $acceptableTypes = [];
public function __construct(array $acceptableTypes = [])
{
$this->acceptableTypes = $acceptableTypes;
}
/**
* @param string $attribute
* @param \Illuminate\Http\UploadedFile $value
*
* @return bool
*/
public function validate($attribute, $value, Closure $fail) : void
{
if(!in_array($value->getClientOriginalExtension(), $this->acceptableTypes))
{
$fail('Invalid document type uploaded');
}
}
}
请注意,它使用 PHP 5.3 中引入的 PHP Closure 功能来报告错误消息。
类的实例化保持不变:
[
'rules' => ['required', new App\Rules\CustomFileRule(['pdf,bdoc,asice,png,jpg'])]
]