【问题标题】:Is there a way to attach a custom validation message when extending the validator in laravel?在 laravel 中扩展验证器时,有没有办法附加自定义验证消息?
【发布时间】:2018-03-02 11:40:55
【问题描述】:

目前我已经实现了以下自定义验证,但是如果验证失败,我不知道如何附加自定义消息。为了澄清,我需要在扩展验证器时定义错误消息

Validator::extend('phone_number', function($attribute, $value, $parameters)
    {
       // is there anyway I could define a error message here, if this validation fails,
        if (strlen($value) === 9)
        {
            if (substr($value, 0, 1) === '0')
            {
                return false;
            }
        }
        else
        {
            if (substr($value, 0, 1) != '0')
            {
                return false;
            }
        }

        return true;
    });

我目前已将此代码放在引导方法中,并且在文档中他们说有一种方法可以定义自定义消息,如下所示,但我真的不明白。

public function boot()
{

Validator::extend(...);

Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
    return str_replace(...);
});

}

【问题讨论】:

  • 您可以简单地添加第三个参数来扩展Validator::extend('phone_number', function($attribute, $value, $parameters){//....}, 'You custom message'); ;)
  • 这就是您要找的吗?
  • 是的,就是这样,你能把这个作为答案发布吗?非常感谢

标签: laravel validation laravel-5 laravel-validation


【解决方案1】:

您可以将自定义验证规则消息放入resources/lang/en/validation.php

也可以看看这个页面:https://laravel-news.com/laravel-5-5-custom-validator-rules

这是创建自定义验证规则的更好方法。

【讨论】:

  • 是的,我知道这种方法,但现在我不能使用它,所以寻找替代方法。
【解决方案2】:

您可以通过向extend 方法添加第三个参数来指定您的消息,如下所示:

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

    if (strlen($value) === 9)
    {
        if (substr($value, 0, 1) === '0')
        {
            return false;
        }
    }
    else
    {
        if (substr($value, 0, 1) != '0')
        {
            return false;
        }
    }

    return true;
}, 'Your custom message goes here'); // <--- HERE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 2017-06-28
    • 2017-12-13
    • 1970-01-01
    相关资源
    最近更新 更多