如何更改Laravel验证消息的最大文件大小以MB代替KB? [英] How to change Laravel Validation message for max file size in MB instead of KB?
问题描述
Laravel随附以下验证消息,该消息显示文件大小(以千字节为单位):
file' => 'The :attribute may not be greater than :max kilobytes.',
我想以显示兆字节而不是千字节的方式对其进行自定义. 因此,对于用户来说,它看起来像:
文档不能大于10 MB."
我该怎么做?
您可以扩展验证器以添加自己的规则,并使用相同的逻辑,而无需转换为kb.您可以将对Validator::extend
的调用添加到AppServiceProvider.
<?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文件中.
Laravel comes with this validation message that shows file size in kilobytes:
file' => 'The :attribute may not be greater than :max kilobytes.',
I want to customize it in a way that it shows megabytes instead of kilobytes. So for the user it would look like:
"The document may not be greater than 10 megabytes."
How can I do that?
You can extend the validator to add your own rule and use the same logic without the conversion to kb. You can add a call to Validator::extend
to your AppServiceProvider.
<?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];
});
}
}
Then to add the error message you can just add it to your validation lang file.
See the section on custom validation rules in the manual
这篇关于如何更改Laravel验证消息的最大文件大小以MB代替KB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!