【问题标题】:Custom Validation Replacers in Laravel 5.1Laravel 5.1 中的自定义验证替换器
【发布时间】:2016-01-13 02:31:26
【问题描述】:

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

我现在有

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

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

这是我的替换函数。

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

【问题讨论】:

    标签: php validation laravel-5.1


    【解决方案1】:

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

    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 的文档非常缺乏替换者需要做什么,所以我希望这对以后的人有所帮助。

    【讨论】:

    • 这里从 Laravel 的 Validator 继承的目的是什么?您似乎没有访问任何内部受保护的方法或成员变量,所以这有点多余。除此之外......你是正确的!投赞成票:D
    • 谢谢,您的评论帮助了我!然而,我得到了一个错误,这在另一个问题中得到了解决。它声明您不应该在自定义类中扩展 Validator,因为这会破坏事情。
    • 这个答案让我走上了正轨。我在验证函数中调用了替换器,如下所示:$validator-&gt;addReplacer('dateInYear', 'App\Services\CustomValidator@replaceDateInYear');
    猜你喜欢
    • 2016-01-23
    • 2016-01-13
    • 2015-10-02
    • 2015-11-24
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    相关资源
    最近更新 更多