【问题标题】:How to specify the default error message when extending the Validation class in Laravel 4在 Laravel 4 中扩展 Validation 类时如何指定默认错误消息
【发布时间】:2013-07-12 21:25:32
【问题描述】:

我使用 make 使用 extend 函数在 Laravel 4 的验证类上扩展和添加自定义规则。

Validator::extend('foo', function($attribute, $value, $parameters)
{
    return $value == 'foo';
});

当我使用新创建的自定义扩展验证规则时,如果规则失败,它将返回 validation.foo。在 Laravel 4 中扩展验证类时,有没有办法定义通用/默认消息?

【问题讨论】:

    标签: validation laravel laravel-4


    【解决方案1】:

    The Laravel 4 docs specifically state您需要为您的自定义规则定义错误消息。

    你有两个选择;

    选项 1:

    $messages = array(
        'foo' => 'The :attribute field is foo.',
    );
    
    $validator = Validator::make($input, $rules, $messages);
    

    选项 2:

    在语言文件中指定您的自定义消息,而不是将它们直接传递给验证器。为此,请将您的消息添加到 app/lang/xx/validation.php 语言文件中的自定义数组中:

    'custom' => array(
        'foo' => array(
            'required' => 'We need to know your foo!',
        ),
    ),
    

    【讨论】:

    • 谢谢,看起来我在浏览验证扩展时完全错过了该部分。感谢您的帮助。
    • 我对@9​​87654324@ 解决方案有疑问。这是否意味着您必须为那里的每个字段指定消息,而不是为您的自定义验证器的所有情况?在这种情况下,custom.foo 可能会被视为字段名称,而不是您的 foo 验证器。并且文档还说 custom 应该仅用于特定字段的自定义错误消息,例如myField.required=>'message'`` and not 'myValidator=>'消息'`。所以,我仍在寻找解决方案,为什么我的自定义验证器不从 validation.php 文件中选择消息。我猜是时候进行调试会话了。也许 L5 改变了它?
    • Laravel 5 以上在 resources/lang/xx, resources/lang/en
    【解决方案2】:

    除了TheShiftExchange 所说的之外,如果您查看该validation.php 语言文件,您将看到您可以指定的所有不同规则。例如,如果您的验证器有这样的条目:

    class ArticleValidator extends Validator
    {
        public static $rules = [
            'create'    => [
                'title'                     => ['required'],
                'slug'                      => ['required', 'regex:([a-z\0-9\-]*)']
            ]
        ];
    
    }
    

    那么您的自定义验证规则可能如下所示:

    'custom' => array(
        'company_article_type_id' => array(
            'required' => 'The slug field is really important',
            'exists' => 'The slug already exists',
        ),
    ),
    

    注意自定义验证规则中的 'required' 和 'exists' 键如何与上述验证器中的键匹配。

    【讨论】:

    • 这些规则特定于“company_article_type_id”字段。但是,如果我想在validation.php 文件中为我完全自定义的验证功能的所有情况定义消息怎么办?出于某种原因,Laravel 5 没有收到我的消息。
    【解决方案3】:

    如果有人想知道 Laravel 5:只需将您的消息添加到所有默认消息下方的 validation.php 中。例如:

    <?php
    
    return [
    // .. lots of Laravel code omitted for brevity ...
    
    "timezone"             => "The :attribute must be a valid zone.",
    
    /* your custom global validation messages for your custom validator follow below */
    
    "date_not_in_future"          => "Date :attribute may not be in future.", 
    

    其中date_not_in_future 是您的自定义函数validateDateNotInFuture。 每次你对任何字段使用规则时,Laravel 都会选择消息,除非你想覆盖特定字段的全局消息,否则你不必使用 custom 数组。

    下面是实现验证器的完整代码。

    自定义验证器(带有用于 date_format 和 date_before 本地化的额外陷阱):

    <?php namespace App\Services\Validation;
    
    use Illuminate\Validation\Validator as BaseValidator;
    
    /**
     * Class for your custom validation functions
     */
    class Validator extends BaseValidator  {
    
        public function validateDateNotInFuture($attribute, $value, $parameters)
        {
            // you could also test if the string is a date at all 
            // and if it matches your app specific format 
            // calling $this->validateDateFormat validator with your app's format 
            // loaded from \Config::get, but be careful - 
            // Laravel has hard-coded checks for DateFormat rule 
            // to extract correct format from it if it exists, 
            // and then use for validateBefore. If you have some unusual format
            // and date_format has not been applied to the field,
            // then validateBefore will give unpredictable results.
            // Your best bet then is to override protected function 
            // getDateFormat($attribute) to return your app specific format
    
            $tomorrow = date('your app date format here',  strtotime("tomorrow"));
    
            $parameters[0] = $tomorrow;
            return $this->validateBefore($attribute, $value, $parameters);
        }
    }
    

    ValidatorServiceProvider 文件:

    <?php namespace App\Providers;
    
    namespace App\Providers;
    
    use App\Services\Validation\Validator;
    use Illuminate\Support\ServiceProvider;
    
    class ValidatorServiceProvider extends ServiceProvider{
    
        public function boot()
        {
            \Validator::resolver(function($translator, $data, $rules, $messages)
            {
                return new Validator($translator, $data, $rules, $messages);
            });
        }
    
        public function register()
        {
        }
    }
    

    然后只需在 config/app.php 中添加一行:

        'App\Providers\RouteServiceProvider',
        'App\Providers\ValidatorServiceProvider', // your custom validation  
    

    【讨论】:

      猜你喜欢
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      相关资源
      最近更新 更多