日期验证 - 如何本地化/翻译字符串"今天"和"明天"

jfo*_*ira 13 laravel laravel-validation

在我的模型中,我使用before和定义了一些日期字段的验证规则after:

'birth_date' => 'required|date|before:today|after:01-jan-1920',
'another_date' => 'required|date|before:tomorrow|after:01-jan-1990',
Run Code Online (Sandbox Code Playgroud)

验证工作正常,但我无法弄清楚如何翻译字符串todaytomorrow验证消息.

validation.php语言文件afterbefore消息是本地化的,但是:date消息的部分仍然显示英文版本todaytomorrow.

"after"            => "The :attribute must be a date after :date.",
"before"           => "The :attribute must be a date before :date.",
Run Code Online (Sandbox Code Playgroud)

我如何在验证消息中本地化这两个词 - todaytomorrow- ?

小智 9

总之,将以下代码添加到 resources/lang/whichever/validation.php

'values' => [
    // or whatever fields you wanna translate
    'birth_date' => [
        // or tomorrow
        'today' => '??'
    ]
]
Run Code Online (Sandbox Code Playgroud)

解释:

https://github.com/laravel/framework/blob/7.x/src/Illuminate/Validation/Concerns/FormatsMessages.php#L319

/**
 * Get the displayable name of the value.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return string
 */
public function getDisplayableValue($attribute, $value)
{
    if (isset($this->customValues[$attribute][$value])) {
        return $this->customValues[$attribute][$value];
    }

    // the key we want
    $key = "validation.values.{$attribute}.{$value}";

    // if the translate found, then use it
    if (($line = $this->translator->get($key)) !== $key) {
        return $line;
    }

    if (is_bool($value)) {
        return $value ? 'true' : 'false';
    }

    return $value;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这对我来说是最好的解决方案:)! (2认同)