Laravel Extended Validation custom message

后端 未结 4 1949
灰色年华
灰色年华 2021-01-04 10:03

I wanted to create this extended validation.

Validator::extend(\'my_custom_validation_rule\', function ($attribute, $value, $parameters) {
   // I guess I s         


        
4条回答
  •  别那么骄傲
    2021-01-04 10:49

    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');
    

提交回复
热议问题