Illogical errors messages
Closed this issue · 1 comments
Let's take this example
$v = new \Valitron\Validator(inputs);
$v->rule('required', ['email', 'name']);
$v->rule('email', 'email');
if the email input is empty the validator will generate two messages ($v->errors();
)
Email is required and email is not valid !!
But logically the validator have to generate only one message error: Email is required, and ignore the second one !
I can validate required fields separately then validate the others, but I think this should be done automatically by the Validator !
Am i right ?
You're not wrong, for your use-case :) It's a bit of a philosophical question: Valitron holds a set of one or more rules and will return an error for each rule that fails. In this case, this may be a bit redundant: if an e-mail is empty, it's never valid obviously. There are however cases where it makes sense to get all errors.
You could do two things I guess: show only the first error in the array, or use a custom function to validate your e-mail if it's not empty:
$validator->rule(function($field, $value){
if (empty($value)){
//empty values are handled by the 'required' rule, so we can safely return true here
return true;
}
//e-mail is not empty, so validate it
return filter_var($value, \FILTER_VALIDATE_EMAIL) !== false;
}, 'email' )->message("{field} is not a valid email address");