I am developing a Laravel application. What I am doing in my application is that I am trying to override the custom validation rule message.
I have validation rules like this in the request class:
[
'name'=> [ 'required' ],
'age' => [ 'required', new OverAge() ],
];
Normally, we override the error message of the rules like this:
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
But how can I do that to the custom validation rule class?
After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.
To edit the validation rule for a custom activity field, select the validation rule from Setup by entering Activities in the Quick Find box, then selecting Activities and choose Task Validation Rules or Event Validation Rules. Enter the properties of your validation rule.
You should add all your validation logic in the passes() function. It should return true or false based on the logic you have written in the function. The message() function returns a string that specifies the error message to be displayed in case the validation fails.
You cannot simply overwrite it with the custom messages of the request. If you take a look at the Validator
class:
/**
* Validate an attribute using a custom rule object.
*
* @param string $attribute
* @param mixed $value
* @param \Illuminate\Contracts\Validation\Rule $rule
* @return void
*/
protected function validateUsingCustomRule($attribute, $value, $rule)
{
if (! $rule->passes($attribute, $value)) {
$this->failedRules[$attribute][get_class($rule)] = [];
$this->messages->add($attribute, $this->makeReplacements(
$rule->message(), $attribute, get_class($rule), []
));
}
}
As you can see, it's simply adding the $rule->message()
directly to the message bag.
However, you can add a parameter for the message in your custom rule's class:
public function __construct(string $message = null)
{
$this->message = $message;
}
Then in your message function:
public function message()
{
return $this->message ?: 'Default message';
}
And finally in your rules:
'age' => ['required', new OverAge('Overwritten message')];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With