【问题标题】:How to change Laravel Validation message for max file size in MB instead of KB?如何将 Laravel 验证消息更改为以 MB 为单位的最大文件大小而不是 KB?
【发布时间】:2016-03-28 15:00:26
【问题描述】:

Laravel 带有这个验证消息,显示文件大小以千字节为单位:

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

我想以显示兆字节而不是千字节的方式对其进行自定义。 所以对于用户来说,它看起来像:

“文档不能超过 10 兆字节。”

我该怎么做?

【问题讨论】:

  • 将规则保留为 :max KB,并为控件添加自定义消息,以 MB 为单位显示大小。
  • @PratikKaje 但是对于 10 MB,我的 :max 是 10240。所以消息会说“文档可能不超过 10240 兆字节。”
  • 您的规则将处理您将在 KB 中提到的最大大小限制。您与规则相关的自定义消息将是一个简单的文本,上面写着“属性可能不超过 20 MB”
  • 不确定我是否完全理解。您是说在消息本身中以 MB 为单位对大小进行硬编码吗?

标签: laravel laravel-5.1 laravel-validation


【解决方案1】:

将resources\lang\en\validation.php中的字符串改为

'file' => ':attribute 不能超过 10 兆字节。',

并将$rule 定义为

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

【讨论】:

  • 但是“max”的 laravel 验证器以 KB 而非 MB 为单位计算大小。 laravel.com/docs/5.1/validation#rule-maxlaravel.com/docs/5.1/validation#rule-size
  • @GladToHelp 好的,那么您可以将规则保留为 10000 KB,并将错误消息硬编码为 10 Mb
  • 但是文件上传限制硬编码在您的消息中,与您输入的值不对应:max
  • @GladToHelp 该规则将在文件超过 10000 kb 时激活。它会触发消息说您的文件超过 10 兆字节,这是真的。 10 兆字节 = 10000 千字节
  • 如果我有一个最大为 5MB 的不同文件上传控件会怎样?那么会是真的吗?
【解决方案2】:

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

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

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

【讨论】:

  • 但是该消息会强制您在整个应用程序中设置 10 MB 的限制,因为它是硬编码在字符串中的(内部没有 :max)。如果 Word 文件的限制为 5MB,而图像文件的限制为 10MB,该怎么办?
  • @PratikKaje,我认为硬编码限制到自定义错误消息中并不灵活。特别是当您从配置文件中配置最大值时。
【解决方案3】:

您可以扩展验证器以添加您自己的规则并使用相同的逻辑而无需转换为 kb。您可以向您的 AppServiceProvider 添加对 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];
        });
    }
}

然后要添加错误消息,您只需将其添加到您的验证语言文件中即可。

See the section on custom validation rules in the manual

【讨论】:

  • 是的,我想扩展验证器是唯一正确的方法
  • 不...我建议使用内置的验证规则“文件”并为该规则创建一个自定义替换器
  • 我想这取决于 OP。如果在团队中工作,添加规则不会改变其他人在使用框架时可能期望的功能。也就是说,上面很容易更改为Validator::replacer('max', ...,如果那是 OP 之后的内容
  • 你说得对,这完全取决于 OP 的意图。问题本身表明他只想让输出以 MB 显示。但是,如果打算在验证规则中提供最大限制为 MB,则验证器扩展是处理此问题的唯一方法。也许您可以在答案中添加一个简短的提示;)
  • 嗨@BenSwinburne。我已经尝试过您的解决方案,并且在我的 lang 文件中我有 'custom' =&gt; [ 'file' =&gt; [ 'max' =&gt; 'The :attribute may not be greater than :max megabytes.', ], ],。但是 laravel 不会将值转换为兆比特。我得到 10240 兆字节。
【解决方案4】:

这就是我将如何使用带有自定义验证消息的请求进行验证,以 MB 而不是 KB:

  1. 在 App\HTTP\Requests 文件夹中创建一个名为 StoreTrackRequest.php 的请求文件,内容如下

    <?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.'
            ];
        }
    }
    
  2. 在控制器内部确保通过 StoreTrackRequest 请求执行验证:

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

【讨论】:

  • 对不起,亲爱的,这个解决方案对我不起作用。谢谢。
【解决方案5】:

文件: 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')

【讨论】:

  • 嗨@Fahmi。您的解决方案也不起作用。我没有收到任何错误,但通常验证不起作用。大于 10MB 的文件不会被阻止。除了upload.max_size 在哪里。函数 config 用于访问 laravel 中的配置值。配置目录和上传的文件不是这些文件之一。
  • @FokwaBest upload.max_size 是我的自定义配置文件,因此您可以像我一样创建文件,也可以硬编码值。你能给你的 php.iniupload_max_filesize 吗?我怀疑这是罪魁祸首,因为如果文件大小大于upload_max_filesize,Laravel 基本上会给出静默错误
  • 你好 @Fahmi 为什么不直接使用 'max_mb' =&gt; 'The :attribute may not be greater than :max_mb MB.' 这样的东西,以便 laravel 可以使用 max_mb 值。因为通常 max_mb 是您在验证规则中使用的。
  • @FokwaBest 我已经改变了。谢谢
【解决方案6】:

这个功能有效

public function getSize()
{
    $mb = 1000 * 1024;

    if ($this->size > $mb)
        return @round($this->size / $mb, 2) . ' MB';
    return @round($this->size / 1000, 2) . ' KB';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2014-08-28
    • 1970-01-01
    相关资源
    最近更新 更多