我创建了一个自定义验证规则:
<?php
namespace AppRules;
use CarbonCarbon;
use IlluminateContractsValidationRule;
class NotOlderThan
{
public function validate($attribute, $value, $parameters, $validator)
{
$maxAge = $parameters[0];
$date = Carbon::parse($value);
return !Carbon::now()->subYears($maxAge)->gte($date);
}
}
我已将其添加到我的服务提供商:中
<?php
namespace AppProviders;
use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesValidator;
class RulesServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Validator::extend('phone', 'App\Rules\Phone');
Validator::extend('not_older_than', 'App\Rules\NotOlderThan');
}
}
我已将resources/lan/en/validation.php
修改为包含以下内容:
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'phone' => 'The :attribute must be a valid :locale number without the country code prefix.',
'not_older_than' => 'Age cannot be older than :maxAge',
现在我可以像这样使用这些自定义验证规则:
$this->validate([
'phone' => 'required|phone',
'dateOfBirth' => 'not_older_than:30',
'issuedAt' => 'not_older_than:10'
]);
现在我遇到的问题是,我希望能够在返回给客户端的验证消息中包含参数,但我不确定该在哪里设置。例如,在上面的例子中'not_older_than' => 'Age cannot be older than :maxAge'
应该返回Age cannot be older than 30 years.
。
所以第二次看文档时,我看到了以下内容,我第一次一定错过了:
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend(...);
Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
return str_replace(...);
});
}
然而,这对我来说并不起作用,因为某种原因,每当我添加这个代码自定义验证器时,它就会停止工作,没有错误,它就是不起作用。所以我环顾四周,在这里找到了一个解决方案,tat建议我改为这样做:
<?php
namespace AppRules;
use CarbonCarbon;
use IlluminateContractsValidationRule;
class NotOlderThan
{
public function validate($attribute, $value, $parameters, $validator)
{
$validator->addReplacer('not_older_than', function ($message, $attribute, $rule, $parameters) {
return str_replace(':age', $parameters[0], $message);
});
$maxAge = $parameters[0];
$date = Carbon::parse($value);
return Carbon::now()->subYears($maxAge)->lte($date);
}
}
在这里,我调用自定义规则类的validate方法中的validator实例,并在其上使用replacer