繁体   English   中英

使用“今天/明天”等参数在“之前”和“之后”验证规则的Laravel本地化

[英]Laravel localization of validation rule 'before' and 'after' with parameter like 'today/tomorrow'

让我们假设我的模型中有这个规则:

public $rules = [           
        'a_date'  => 'after:today',
        'b_date'  => 'before:today',
    ];

我在我的project\\resources\\lang\\en\\validation.php有这个字符串:

    'after' => 'The :attribute must be a date after :date.',
    'before' => 'The :attribute must be a date before :date.',

我将它们翻译成project\\resources\\lang\\some-language\\validation.php

    'after' => ':attribute *somelanguage* :date.',
    'before' => ':attribute *somelanguage* :date.',

但是当我在我的应用程序中遇到验证错误时,我看到这样的字符串: *field* *some language* today
(例如俄语: Поле a_date должно быть раньше чем today

所以问题是today如何以及在何处将这个( 以及任何其他类似的预测词 )替换为所需的本地化?

PS:我可以使用docs https://laravel.com/docs/5.2/validation#localization中所述的自定义验证
但它只能应用。查阅全文某些领域,我希望它来代替today ,每当我在任何领域的使用。

在lang文件中创建一个数组(在我的例子中是title.php ):

'time_periods' => [
        'yesterday' => 'вчера',
        'now'       => 'сейчас',
        'today'     => 'сегодня',
        'tomorrow'  => 'завтра',
    ],

然后在CustomValidator类中添加以下代码:
所有这些代码都使用此数组的键替换某些规则中的参数和lang文件数组中的值。 首先,它将英语替换者更改为本地化替换者,然后使用它替换验证消息中的实际占位符( :date )。

    class CustomValidator extends Validator {
        public function replaceBefore($message, $attribute, $rule, $parameters) {                
            $parameter_translated = str_replace(
                array_keys(trans('title.time_periods')),
                array_values(trans('title.time_periods')), 
                $parameters[0]
            );
            return str_replace(':date', $parameter_translated, $message);
        }

        // this method does the same but for 'after' rule
        public function replaceAfter($message, $attribute, $rule, $parameters) {
            $parameter_translated = str_replace(array_keys(trans('title.time_periods')), array_values(trans('title.time_periods')), $parameters[0]);
            return str_replace(':date', $parameter_translated, $message);
        }
    }

如果您不喜欢使用CustomValidator ,请使用此方法(从文档中获取 ,请参阅:'定义错误消息'部分):

创建自定义验证规则时,有时可能需要为错误消息定义自定义占位符替换。 您可以通过如上所述创建自定义Validator,然后在Validator外观上调用replacer方法来实现。 您可以在服务提供者的引导方法中执行此操作:

 /** * Bootstrap any application services. * * @return void */ public function boot() { Validator::extend(...); Validator::replacer('foo', function($message, $attribute, $rule, $parameters) { return str_replace(...); }); } 

暂无
暂无

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

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