在Laravel 4.2中执行自定义错误消息

时间:2015-09-25 04:19:46

标签: laravel laravel-4 laravel-validation

我是Larvel 4.2的新手!如何在Laravel 4.2中执行自定义错误消息?我在哪里放这些代码?我一直在使用默认值,我有点想使用自己的默认值。

2 个答案:

答案 0 :(得分:1)

你尝试过什么? http://laravel.com/docs/4.2/validation#custom-error-messages

您使用过Google吗?检查文档(官方)它有一切。不要太懒惰。

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

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

答案 1 :(得分:1)

要添加到光滑所给出的答案,以下是如何在控制器内的存储功能的实际示例中使用它:

public function store(Request $request)
    {    
        $validator = Validator::make($request->all(), [
            'id1' => 'required|between:60,512',
            'id2' => 'required|between:60,512',
            'id3' => 'required|unique:table',
        ], [
            'id1.required' => 'The first field is empty!',
            'id2.required' => 'The second field is empty!',
            'id3.required' => 'The third field is empty!',
            'id1.between' => 'The first field must be between :min - :max characters long.',
            'id2.between' => 'The second answer must be between :min - :max characters long.',
            'id3.unique' => 'The third field must be unique in the table.',
        ]);

        if ($validator->fails()) {
            return Redirect::back()
                ->withErrors($validator)
                ->withInput();
        }

        //... Do something like store the data entered in to the form
}

id应该是您要验证的表单中字段的ID。

您可以查看可以使用的所有规则here