如果有人想知道 Laravel 5:只需将您的消息添加到所有默认消息下方的 validation.php 中。例如:
<?php
return [
// .. lots of Laravel code omitted for brevity ...
"timezone" => "The :attribute must be a valid zone.",
/* your custom global validation messages for your custom validator follow below */
"date_not_in_future" => "Date :attribute may not be in future.",
其中date_not_in_future 是您的自定义函数validateDateNotInFuture。
每次你对任何字段使用规则时,Laravel 都会选择消息,除非你想覆盖特定字段的全局消息,否则你不必使用 custom 数组。
下面是实现验证器的完整代码。
自定义验证器(带有用于 date_format 和 date_before 本地化的额外陷阱):
<?php namespace App\Services\Validation;
use Illuminate\Validation\Validator as BaseValidator;
/**
* Class for your custom validation functions
*/
class Validator extends BaseValidator {
public function validateDateNotInFuture($attribute, $value, $parameters)
{
// you could also test if the string is a date at all
// and if it matches your app specific format
// calling $this->validateDateFormat validator with your app's format
// loaded from \Config::get, but be careful -
// Laravel has hard-coded checks for DateFormat rule
// to extract correct format from it if it exists,
// and then use for validateBefore. If you have some unusual format
// and date_format has not been applied to the field,
// then validateBefore will give unpredictable results.
// Your best bet then is to override protected function
// getDateFormat($attribute) to return your app specific format
$tomorrow = date('your app date format here', strtotime("tomorrow"));
$parameters[0] = $tomorrow;
return $this->validateBefore($attribute, $value, $parameters);
}
}
ValidatorServiceProvider 文件:
<?php namespace App\Providers;
namespace App\Providers;
use App\Services\Validation\Validator;
use Illuminate\Support\ServiceProvider;
class ValidatorServiceProvider extends ServiceProvider{
public function boot()
{
\Validator::resolver(function($translator, $data, $rules, $messages)
{
return new Validator($translator, $data, $rules, $messages);
});
}
public function register()
{
}
}
然后只需在 config/app.php 中添加一行:
'App\Providers\RouteServiceProvider',
'App\Providers\ValidatorServiceProvider', // your custom validation