【问题标题】:Laravel localization of validation rule 'before' and 'after' with parameter like 'today/tomorrow'验证规则“之前”和“之后”的 Laravel 本地化,参数类似于“今天/明天”
【发布时间】:2016-10-02 06:51:50
【问题描述】:

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

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:我可以使用文档https://laravel.com/docs/5.2/validation#localization
中所述的自定义验证,但它仅适用于某些字段,我希望每当我在任何字段中使用它时都能替换today

【问题讨论】:

    标签: php validation laravel date laravel-5


    【解决方案1】:

    在您的 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,请使用此方法(取自 the documentation,请参阅:“定义错误消息”部分):

    创建自定义验证规则时,您有时可能需要 为错误消息定义自定义占位符替换。你可以做 因此,通过如上所述创建自定义验证器,然后制作 调用 Validator 门面的 replacer 方法。你可以这样做 在服务提供者的引导方法中:

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

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2020-09-16
      相关资源
      最近更新 更多