首页 > 解决方案 > 在自定义验证规则的消息中包含参数

问题描述

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

<?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.在上面的例子中返回。

标签: laravelvalidationlaravel-validation

解决方案


因此,第二次查看文档时,我看到了以下内容,我一定是第一次错过了:

/**
 * 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 方法中调用验证器实例,并在其上使用替换器。这对我有用。


推荐阅读