如何更改Laravel验证消息的最大文件大小为MB而不是KB?

sy5wg1nm  于 2023-05-01  发布在  其他
关注(0)|答案(7)|浏览(202)

Laravel附带了以下验证消息,以KB为单位显示文件大小:

file' => 'The :attribute may not be greater than :max kilobytes.',

我想自定义它的方式,它显示兆字节,而不是千字节。对于用户来说,它看起来像:
“文档不能大于10兆字节。“
我该怎么做?

q9rjltbz

q9rjltbz1#

这是我使用Request进行验证的方式,自定义验证消息以MB而不是KB为单位:
1.创建名为StoreTrackRequest的请求文件。php在App\HTTP\Requests文件夹中,内容如下

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class StoreTrackRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            "name" => "required",
            "preview_file" => "required|max:10240",
            "download_file" => "required|max:10240"
        ];
    }

    /**
     * Get the error messages that should be displayed if validation fails.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'preview_file.max' => 'The preview file may not be greater than 10 megabytes.',
            'download_file.max' => 'The download file may not be greater than 10 megabytes.'
        ];
    }
}

1.在控制器内部,确保通过StoreTrackRequest请求执行验证:

public function store($artist_id, StoreTrackRequest $request)
{
     // Your controller code
}
nbysray5

nbysray52#

Laravel 8
以生成新的验证规则。

php artisan make:rule MaxSizeRule

如下所示编辑规则。

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class MaxSizeRule implements Rule
{
    private $maxSizeMb;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($maxSizeMb = 8)
    {
        $this->maxSizeMb = $maxSizeMb;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $megabytes = $value->getSize() / 1024 / 1024;

        return $megabytes < $this->maxSizeMb;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute may not be greater than ' . $this->maxSizeMb . ' MB.';
    }
}

在您的验证请求中使用如下

return [
    ...
    'banner_image' => ['required', 'file', 'mimes:jpeg,png,jpg,svg', new MaxSizeRule(10)],
    ...
];
flvlnr44

flvlnr443#

更改resources\lang\en\validation中的字符串。php到
'file' =〉':属性不能大于10兆字节。',
并将$rule定义为

$rules = array(
   'file'=>'max:10000',
);
bq9c1y66

bq9c1y664#

我们可能在不同的页面上,这就是我想说的。希望这能帮上忙。干杯!

public function rules()
{
    return [
        'file' => 'max:10240',
     ];
}

public function messages()
{
    return [
        'file.max' => 'The document may not be greater than 10 megabytes'
    ];
}
s2j5cfk0

s2j5cfk05#

**文件:**app/Providers/AppServiceProvider。PHP

public function boot()
{
    Validator::extend('max_mb', function ($attribute, $value, $parameters, $validator) {

        if ($value instanceof UploadedFile && ! $value->isValid()) {
            return false;
        }

        // SplFileInfo::getSize returns filesize in bytes
        $size = $value->getSize() / 1024 / 1024;

        return $size <= $parameters[0];

    });

    Validator::replacer('max_mb', function ($message, $attribute, $rule, $parameters) {
        return str_replace(':' . $rule, $parameters[0], $message);
    });
}

不要忘记导入适当的类。

**文件:**resources/lang/en/validation。PHP

'max_mb' => 'The :attribute may not be greater than :max_mb MB.',

'accepted'             => 'The :attribute must be accepted.',
'active_url'           => 'The :attribute is not a valid URL.',
...

相应地更改config('upload.max_size')

2skhul33

2skhul336#

您可以创建自己的规则,并使用与现有规则相同的逻辑,但无需转换为KB。
为此,在AppServiceProvider.php文件中添加对Validator::extend方法的调用,如:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('max_mb', function($attribute, $value, $parameters, $validator) {
            $this->requireParameterCount(1, $parameters, 'max_mb');

            if ($value instanceof UploadedFile && ! $value->isValid()) {
                return false;
            }

            // If call getSize()/1024/1024 on $value here it'll be numeric and not
            // get divided by 1024 once in the Validator::getSize() method.

            $megabytes = $value->getSize() / 1024 / 1024;

            return $this->getSize($attribute, $megabytes) <= $parameters[0];
        });
    }
}

然后,要更改错误消息,只需编辑验证lang文件即可。

另请参见手册中自定义验证规则部分

moiiocjp

moiiocjp7#

此功能有效

public function getSize()
{
    $kb = 1024;
    $mb = $kb * 1024;
    
    if ($this->size > $mb)
        return @round($this->size / $mb, 2) . ' MB';
    return @round($this->size / $kb, 2) . ' KB';
}

相关问题