valitron
valitron copied to clipboard
Adding labels with similar syntax like Alternate syntax for adding rules
Hi Can we set all labels using an array with a syntax similar to Alternate syntax for adding rules. I was thinking something like this
` $messages = [ 'required' => '{field} is required', 'accepted' => '{field} was rejected' ];
$v = new Valitron\Validator(array('foo' => 'bar', 'bar' => 1)); $v->labels($messages); $v->validate(); ` Any examples will be appreciated Thanks
There is a labels() method, but it doesn't do what I think you want. It only sets the {field} part of an error message. An example can be found in the tests here: https://github.com/vlucas/valitron/blob/master/tests/Valitron/ErrorMessagesTest.php#L40
I think what you want is something to set all or some messages for rules, kind of like when they are loaded from the language files. This is not possible right now, but it's a good idea.
Probably the easiest way to do this right now is by creating your own language file and load those in the constructor:
$v = new Validator($data, $fields, "en-custom", "/path/to/my-language-files"
This will try to load the messages from /path/to/my-language-files/en-custom.php
Am not taking about language files
Take a look at this line
$v->rule('required', 'name')->message('{field} is
required');I need a way to set the messages for each field using an array Like so $messages = [ 'required' => 'field} is required' ]
$v->messages($messages);`
Well yeah, that's what the language files do: they hold a default message for every rule.
(they are really 'message' files, using them for language is just the main way Valitron uses them out of the box)
I wish this option is added in next release. It will also be great to have an array passed through the constructor rather than a file path That way we can separate loading of files from the actual validator. A setLangPath method could be added as an option as well.
I can try to add the messages() method (or you can try it too :)), but for the time being we won't be changing the constructor options.