【问题标题】:How to set multi-language name to a db field in validation error message on laravel4如何在 laravel4 上的验证错误消息中将多语言名称设置为 db 字段
【发布时间】:2013-11-13 02:23:27
【问题描述】:

我对如何在 laravel 4 验证后管理错误消息中的数据库字段名称有一点疑问。

为了验证表单,我使用了 eloquent,如下所示:

public static function validate($input)
    {
        $validation = array(
            'rules' => array(
                'title'     => 'required|min:5'
            ),
            'messages' => array(
                'title.required'            => 'Inserer un titre!'
            )
        );

        return Validator::make($input, $validation['rules'], $validation['messages']);
    }

为了翻译错误信息,我使用了这个 github 仓库:https://github.com/caouecs/Laravel4-lang

除了属性(db 列)名称的翻译外,一切都很好。我不知道该怎么做,有什么建议吗?

fr : Le texte **title** doit contenir au moins 5 caractères.
en : The **title** must be at least 5 characters.

(在每种情况下标题都保持英文。)

【问题讨论】:

标签: php laravel laravel-4


【解决方案1】:

有两种方法可以为验证错误消息提供自定义字段名称。

首先是使用语言配置文件 app/lang/LANG/validation.php

/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/

'attributes' => array('foo' => 'Bar'),

这将为 foo 字段生成验证错误,例如“The Bar must be...”而不是“The foo must be ...”。

第二种方式没有记录。您可以使用 Validator 类的 setAttributeNames() 方法在运行时提供自定义数组:

    $validator = Validator::make($input, $rules, $messages);
    $validator->setAttributeNames(array('foo' => 'Bar'));
    if ($validator->passes())
        ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 2011-03-31
    • 2022-12-21
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多