Gla*_*elp 5 laravel laravel-validation laravel-5.1
Laravel附带此验证消息,显示以千字节为单位的文件大小:
file' => 'The :attribute may not be greater than :max kilobytes.',
Run Code Online (Sandbox Code Playgroud)
我想以一种显示兆字节而不是千字节的方式自定义它.所以对于用户来说,它看起来像:
"该文件可能不会超过10兆字节."
我怎样才能做到这一点?
我们可能处于不同的页面,这就是我想说的。我希望这有帮助。干杯!
public function rules()
{
return [
'file' => 'max:10240',
];
}
public function messages()
{
return [
'file.max' => 'The document may not be greater than 10 megabytes'
];
}
Run Code Online (Sandbox Code Playgroud)
您可以创建自己的规则,并使用与现有规则相同的逻辑,但无需转换为 KB。
为此,请Validator::extend在文件中添加对方法的调用AppServiceProvider.php,例如:
<?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];
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后要更改错误消息,您只需编辑验证语言文件即可。
另请参阅手册中有关自定义验证规则的部分
| 归档时间: |
|
| 查看次数: |
5878 次 |
| 最近记录: |