Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override the message of the custom validation rule in Laravel?

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?

like image 658
Wai Yan Hein Avatar asked May 30 '19 19:05

Wai Yan Hein


People also ask

What is the method used for specifying custom messages for validation errors in form request?

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.

How do you change a validation rule?

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.

What methods should you implement for your custom validator laravel?

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.


1 Answers

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')];
like image 86
Chin Leung Avatar answered Nov 09 '22 09:11

Chin Leung