【发布时间】:2020-08-21 22:01:10
【问题描述】:
我创建了一个自定义验证规则:
<?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.。
【问题讨论】:
标签: laravel validation laravel-validation