如何在Laravel 4中扩展Validation类时指定默认错误消息

时间:2013-07-15 05:00:31

标签: validation laravel laravel-4

我使用extend函数在Laravel 4的Validation Class上扩展和添加自定义规则。

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

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

3 个答案:

答案 0 :(得分:9)

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

您有两种选择;

选项1:

$messages = array(
    'foo' => 'The :attribute field is foo.',
);

$validator = Validator::make($input, $rules, $messages);

选项2:

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

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

答案 1 :(得分:1)

如果有人想知道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  

答案 2 :(得分:0)

除了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'键如何与上面验证器中的键匹配。