You can set your own custom error messages by using the messages()
method. This can be handy when using translations. You can overwrite rule messages globally or set a message per rule and field name.
use KrisKuiper\Validator\Validator;
$data = [
'amount' => 4,
'product' => 'Laptop'
];
$validator = new Validator($data);
$validator
->field('amount', 'product')
->required();
//Set error message globally for the required rule
$validator
->messages()
->required('Field is required!');
use KrisKuiper\Validator\Validator;
$data = [
'amount' => 4,
'product' => 'Laptop'
];
$validator = new Validator($data);
$validator->field('amount', 'product')->required();
//Sets the required error messages specific for the amount field
$validator
->messages('amount')
->required('Amount is required!');
//Sets the required error messages specific for the product field
$validator
->messages('product')
->required('Product is required!');
use KrisKuiper\Validator\Validator;
$data = [
'amount' => 4,
'product' => 'Laptop'
];
$validator = new Validator($data);
$validator
->field('amount', 'product')
->required();
//Sets the required error messages specific for the amount field
$validator
->messages('amount')
->required('Amount is required');
//Set error message globally for the required rule. This will only affect the product field in this example.
$validator
->messages()
->required('Field is required');
You can use the parameters name of the rule as placeholders. For example, the between rule, has two parameters named $minimum
and $maximum
. The placeholders will be replaced with their corresponding parameter values.
use KrisKuiper\Validator\Validator;
$data = [
'amount' => 4,
'product' => 'Laptop'
];
$validator = new Validator($data);
$validator
->field('amount')
->between(1, 5); //$minimum and $maximum parameters
$validator
->messages('amount')
->between('Amount should be between :minimum and :maximum');
//Amount should be between 1 and 5'
You can set custom error messages within custom rule closures or custom rule class objects using the message()
method:
use KrisKuiper\Validator\Validator;
$data = ['amount' => 5];
$validator = new Validator($data);
//Define the customer rule
$validator->custom('myCustomRule', function (Event $event): bool {
$event->message('Amount should be at least :min');
return $event->geValue() >= $event->getParameter('min');
});
//Attach the custom rule to the amount field
$validator->field('amount')->custom('myCustomRule', ['min' => 10]);
Go to the previous section.
Go to the next section.