Laravel Custom Extended Validation Post

I wanted to create this extended validation.

Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) {
   // I guess I should be setting the error message for this here.(Its dynamic)
   // We can return true or false here depending upon our need.  
}

      

I would use this rule like this

'my_field' => 'required|my_custom_validation_rule'

,

I want to use a dynamic message for the error " my_custom_validation_rule

"

I was unable to find anything from the documentation about this. Is there anyway to do it?

+9


source to share


4 answers


The method extend

allows you to pass a message as the third argument:

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

      



By default, you can only use a dynamic variable :attribute

. If you want to add more usage Validator::replacer()

:

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

      

+26


source


You can also define a message for your custom validation rule in the validation files 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.'

      

+3


source


Possible (not very elegant) workaround:

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

      

0


source


Basically, this is similar to @ lukasgeiter's answer, but in case you need to manage a dynamic variable inside an extension function, you can use it $validator->addReplacer

inside an extension directly.

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

    // Test custom message
    $customMessage = request()->get('foo') 
        ? "Foo does not 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');

      

0


source







All Articles