Hi everyone and thanks for your help. I'll like to custom error messages for validation and eventually to create different version for each language, it's possible ?
Here my code in his actually state.
namespace App;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator as v;
class Validator {
private $messages = [
'lastname',
'firstname',
'phone',
'email',
'message'
];
//other functions and declarations of my class.
private function validationData() {
$rule = null;
switch ($this->page) {
case 'contact';
$rule = v::key('lastname', v::notEmpty()
->alpha("-'"))
->key('firstname', v::optional(v::alpha("-'")))
->key('phone', v::optional(v::phone()))
->key('email', v::email())
->key('message', v::optional(v::length(5, 500)));
break;
default;
break;
}
try {
$rule->assert($this->data);
} catch (ValidationException $exception) {
var_dump($exception->findMessages($this->messages));
}
}
}
It returns me that:
array(5) {
["lastname"]=> string(51) "lastname must contain only letters (a-z) and ""-'"""
["firstname"]=> string(0) ""
["phone"]=> string(38) "phone must be a valid telephone number"
["email"]=> string(25) "email must be valid email"
["message"]=> string(44) "message must have a length between 5 and 500"
}
I need to keep this structure of my result of validation. Because I need field's names for could to display them at client side.
Thanks again,
You can do it with Respect/Validation.
When you define your messages, just make it an associative array with the key that represents the error and the value the message that will be shown:
You can create a custom function that converts the messages in any language you want to:
and then use it in your catch block: