Reputation: 875
I've read the docs and I wonder if its possible to make custom messages based on rules AND attribute, for example I have the following code
$casoValidator = Validator::attribute('nombre',Validator::allOf(Validator::stringType(),Validator::notOptional(),
Validator::stringType()->length(3,100))) //nombre, validamos que sea cadena, que es obligatorio y que tiene de 3 a 100 caracteres
->attribute('idUsuario',Validator::allOf(Validator::intType()))
->attribute('numeroSertel',Validator::allOf(Validator::stringType(), Validator::stringType()->length(1,100)))
->attribute('dni',Validator::allOf(Validator::stringType(), Validator::stringType()->length(8,20))); //la capturaremos al hacer insert si hay problemas con las FK
try {
$asuntoValidator->assert($asunto);
} catch(NestedValidationException $exception) {
$errors = $exception->findMessages([
'length' => '{{name}} no puede tener mas de 100 caracteres ni menos de uno',
'notOptional' => '{{name}} no es opcional',
....
as you can see, I have different length for 'nombre' and 'dni' so I should return two different messages, one that says you can't have less than 3 character nor more than 100 and for dni I should return that dni can't have less than 8 charactes nor more than 20
is there a way to do it?
Upvotes: 2
Views: 538
Reputation: 1665
Add a separate setTemplate
method call for each rule that is required for the custom template. For ex.:
$rule = v::key('color', v::alnum()->setTemplate('{{name}} must be alphanumeric value, for ex. f7f1d5'))
->key('color', v::length(6,6)->setTemplate('{{name}} must be a 6-character value'));
$params['color'] = '¯\_(ツ)_/¯';
try{
$rule->assert($params);
} catch (NestedValidationException $e) {
$errors = $e->getMessages();
}
var_dump($errors);
Result:
array (size=2)
0 => string 'color must be alphanumeric value, for ex. f7f1d5' (length=48)
1 => string 'color must be a 6-character value' (length=33)
Upvotes: 1