Laravel 5.4 - How to use multiple error messages for the same custom validation rule

后端 未结 4 1825
失恋的感觉
失恋的感觉 2021-02-19 21:40

In order to reuse code, I created my own validator rule in a file named ValidatorServiceProvider :

class ValidatorServiceProvider extends Servic         


        
4条回答
  •  粉色の甜心
    2021-02-19 22:41

    Alternatively to the other proposals, I think you could also call Validator::replacer('yourRule', function()) in addition to Validator::extend('yourRule', function(...)) and keep track of what causes validation failures in the service provider class you're extending the validator from. This way, you are be able to completely replace the default error message with another one.

    According to docs, replacer() is meant for making placeholder replacements in the error message before it is being returned, so while this is not strictly that case, it is close enough. Of course, it's kind of an ugly(ish) workaround, but it will probably work (at least it seems to work for me, at a first glance).

    One thing to keep in mind though is that you'll probably have to keep track of these failure causes in an array if you want to avoid automatically returning same message for all fields that failed your custom validation rule.

提交回复
热议问题