如何在laravel 5中提供自定义验证消息

时间:2015-03-02 13:49:59

标签: php laravel laravel-5

我一直在关注laravel 4.2并且一天尝试了laravel 5.

如何在laravel 5中为规则添加自定义验证消息。

代码示例        

namespace App\Http\Requests;

 
use App\Http\Requests\Request;
 

class MyRequest extends Request {


    /**

     * Determine if the user is authorized to make this request.

     *

     * @return bool

     */

    public function authorize()

    {

        return true;

    }

 

    /**

     * Get the validation rules that apply to the request.

     *

     * @return array

     */

    public function rules()

    {

        return [

            'email' => 'required|email',

            'password' => 'required|min:8'

        ];

    }

}
// in your controller action
public function postLogin(\App\Http\Requests\MyRequest $request)

{

    // code here will not fire

    // if the validation rules

    // in the request fail

}

?>

它不像4.2中那样清楚

2 个答案:

答案 0 :(得分:3)

您可以像使用规则一样从messages()方法返回它们:

public function messages(){
    return [
        'required' => 'The :attribute field is required.'
    ];
}

答案 1 :(得分:3)

messages()方法外,您还可以在lang文件(resources/lang/[language]/validation.php)中执行此操作,如果您要做的就是更改,例如电子邮件字段上的唯一规则的消息您可以在整个应用中执行以下操作:

/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/

'custom' => [
    'attribute-name' => [
        'rule-name' => 'custom-message',
    ],
    'email' => [
        'unique' => 'This email is already registered...etc',
    ]
],