我创建了一个自定义验证规则:
<?php
namespace App\Rules;
use Carbon\Carbon;
use Illuminate\Contracts\Validation\Rule;
class NotOlderThan
{
public function validate($attribute, $value, $parameters, $validator)
{
$maxAge = $parameters[0];
$date = Carbon::parse($value);
return !Carbon::now()->subYears($maxAge)->gte($date);
}
}
我已经在ServiceProvider中添加了它:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
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(...);
});
}
但是,这对我不起作用,由于某种原因,每当我添加此代码时,自定义验证器就会停止工作,没有错误,那就是行不通的。所以我环顾四周,在这里找到了一个解决方案,建议我以这种方式尝试:
<?php
namespace App\Rules;
use Carbon\Carbon;
use Illuminate\Contracts\Validation\Rule;
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方法中调用了验证器实例,并在其上使用了替换器。这对我有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句