Laravel Extended Validation custom message

筅森魡賤 提交于 2019-12-01 16:00:54

The extend method allows to pass the message as a third argument:

Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) {
    // ...
}, 'my custom validation rule message');

By default you can only use dynamic variable, which is :attribute. If you want to add more use Validator::replacer():

Validator::replacer('my_custom_validation_rule', function($message, $attribute, $rule, $parameters){
    return str_replace(':foo', $parameters[0], $message);
});

You can also define the message for your custom validation rule under validation translations file.

/resources/lang/en/validation.php

....
'unique'                    => 'The :attribute has already been taken.',
'uploaded'                  => 'The :attribute failed to upload.',
'url'                       => 'The :attribute format is invalid.',
//place your translation here
'my_custom_validation_rule' => 'The :attribute value fails custom validation.'

possible (not very elegant) workaround is :

$message = 'my custom validation rule message' . request()->get('param');
Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) {
    //
}, $message);

This is basically the same way as @lukasgeiter answer, but in case you need to manage dynamic variable inside the extend function, you can use $validator->addReplacer inside the extend directly.

Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters, $validator) {

    // Test custom message
    $customMessage = request()->get('foo') 
        ? "Foo doesn't exist"
        : "Foo exist";

    // Replace dynamic variable :custom_message with $customMessage
    $validator->addReplacer('my_custom_validation_rule', 
        function($message, $attribute, $rule, $parameters) use ($customMessage) {
            return \str_replace(':custom_message', $customMessage, $message);
        }
    );

    // Test error message. (Make it always fail the validator)
    return false;

}, 'My custom validation rule message. :custom_message');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!