在消息中包含用于自定义验证规则的参数

问题描述

我创建了一个自定义验证规则:

<?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.

解决方法

第二遍看docs时,我看到了我一定是第一次错过的以下内容:

/**
 * 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',$parameters) {
            return str_replace(':age',$parameters[0],$message);
        });

        $maxAge = $parameters[0];
        $date = Carbon::parse($value);

        return Carbon::now()->subYears($maxAge)->lte($date);
    }
}

在这里,我在自定义规则类的validate方法中调用验证器实例,并在其上使用替换器。这对我有用。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...