Respect / Validation

The most awesome validation engine ever created for PHP
https://respect-validation.readthedocs.io
MIT License
5.76k stars 774 forks source link

Translation from array #1377

Closed programulin closed 1 year ago

programulin commented 2 years ago

Hi! Why there is no way to set all messages from array? Sample:

$translation = [
  'between' => [
    'default' => '{{name}} must be between {{minValue}} and {{maxValue}}',
    'negative' => '{{name}} must not be between {{minValue}} and {{maxValue}}',
  ]
];

Factory::setDefaultInstance(
    (new Factory())->withTranslationArray($translation)
);

Easy to use and share translation files with other people.

Actually, i want to use this lib in Laravel projects with default validator cas i need FormRequests, and my rules seems like:

return [
  'test' => helper(v::stringType()->length(1,20)->noWhitespace()),
];

And its works great, but only problem is translation. I want to use custom messages without any translation libs.

programulin commented 2 years ago

Found a temprorary solution with arrays, Not ideal, but works for now.

$arr = [
  '{{name}} must be of type string' => 'Поле "{{name}}" должно быть строкой',
  '{{name}} must be between {{minValue}} and {{maxValue}}' => 'Поле "{{name}}" должно быть между {{minValue}} и {{maxValue}}',
  'All of the required rules must pass for {{name}}' => 'Выполнены не все условия для поля {{name}}'
];

Factory::setDefaultInstance(
  (new Factory())->withTranslator(function($v1) use ($arr) {
    return $arr[$v1];
  })
);
alganet commented 1 year ago

That is pretty much the recommended way of doing it. Or keeping the array inside the closure, as shown in:

https://github.com/Respect/Validation/blob/master/tests/integration/translator-assert.phpt

Can you elaborate on why this isn't ideal for your case?

alganet commented 1 year ago

I'm closing this because it has almost an year, but feel free to reopen if you're still invested on the discussion!