【问题标题】:respect validation translation issue尊重验证翻译问题
【发布时间】:2021-12-29 20:42:19
【问题描述】:

我一直在使用尊重验证 1.1,并使用下面的代码来翻译消息。

    foreach ($rules as $field => $rule) {
    try {
        $localeField = $translator->trans($field);
        $rule->setName($localeField)->assert($request->getParam($field));
    } catch (NestedValidationException $e) {
        $translateMessage = function($message) use ($translator){
            return $translator->trans($message);
        };
        $e->setParam('translator', $translateMessage);
        $this->errors[$field] = $e->getMessages();
    }

现在我使用的是 2.2 版本的验证,在这个版本中,没有用于错误对象的 setParam 函数。 所以我想知道如何在这个版本中翻译消息。 请帮忙! 提前致谢。

【问题讨论】:

    标签: respect-validation


    【解决方案1】:

    消息的翻译是a bit different in the new version,因为您必须使用工厂来声明默认实例的构建方式。

    我在这里包含一个我在Respect/Validation integration tests 中找到的示例:

    use Respect\Validation\Exceptions\ValidationException;
    use Respect\Validation\Factory;
    use Respect\Validation\Validator;
    
    Factory::setDefaultInstance(
        (new Factory())
            ->withTranslator(static function (string $message): string {
                return [
                    '{{name}} must be of type string' => '{{name}} deve ser do tipo string',
                ][$message];
            })
    );
    
    try {
        Validator::stringType()->length(2, 15)->check(0);
    } catch (ValidationException $exception) {
        echo $exception->getMessage();
    }
    

    您将在此处看到的输出是 0 deve ser do tipo string 字符串。

    【讨论】:

      猜你喜欢
      • 2015-03-09
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      相关资源
      最近更新 更多