Laravel 5.1中的自定义验证替换器


Custom Validation Replacers in Laravel 5.1

我正在尝试在我的Laravel 5.1应用程序中创建一个自定义验证替换器。

我现在有

Validator::replacer('year', 'App'CustomValidators@replaceYear');

在我的AppServiceProvider文件中,在我的自定义类中有相应的活动。但是,当我在验证消息中包含:year时,它不会被替换。我错过了什么?

这是我的替换函数。

public function replaceYear($message, $attribute, $rule, $parameters)
{
    return str_replace([':year'], $parameters, $message);
}

我真正应该做的是像这样设置我的替换器:

Validator::replacer('dateInYear', 'App'CustomValidators@replaceDateInYear');

dateInYear名称对应于我设置的自定义验证规则的名称。但是,我最终做的是扩展验证器类,这样我就不再需要声明每一个自定义规则和替换器了。我的验证器类现在看起来像这样:

<?php
namespace App'Services;
use Carbon'Carbon;
use 'Illuminate'Validation'Validator;
class CustomValidator extends Validator
{
    /**
     * The new validation rule I want to apply to a field. In this instance,
     * I want to check if a submitted date is within a specific year
     */
    protected function validateDateInYear($attribute, $value, $parameters, $validator)
    {
        $date = Carbon::createFromFormat('m/d/Y', $value)->startOfDay();
        if ($date->year == $parameters[0]) {
            return true;
        }
        return false;
    }
    //Custom Replacers
    /**
     * The replacer that goes with my specific custom validator. They
     * should be named the same with a different prefix word so laravel
     * knows they should be run together.
     */
    protected function replaceDateInYear($message, $attribute, $rule, $parameters)
    {
        //All custom placeholders that live in the message for
        //this rule should live in the first parameter of str_replace
        return str_replace([':year'], $parameters, $message);
    }
}

这让我在很大程度上不去管AppServiceProvider文件,只需要注册新的验证类,我真的可以在任何服务提供商中这样做。

Laravel的文档特别缺乏关于替换程序需要发生什么,所以我希望这对将来的人有所帮助。