繁体   English   中英

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的文档特别缺乏替换者需要发生的事情,所以我希望这可以帮助有人在路上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM