0

I have been using respect validation 1.1 and I used below code for translating messages.

    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();
    }

Now I'm using respect validation version 2.2 and in this version there is no setParam function for error object. So I'm wondering how I'm able to translate messages in this version. Please help! thanks in advance.

Miky
  • 11
  • 1
  • 4

1 Answers1

0

Translation of messages is a bit different in the new version, since you have to use a factory to declare how the default instance is built.

I include here an example that I found in the 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();
}

What you will see here as output is the 0 deve ser do tipo string string.

Davide Pastore
  • 8,678
  • 10
  • 39
  • 53