Laravel:自定义表单请求中的自定义验证消息

时间:2018-03-28 15:28:44

标签: php laravel validation

我正在尝试保持控制器清洁并将自定义请求验证移动到单独的类中:

public function register(RegisterUserRequest $request)

并在那里定义所有常用功能,例如

public function rules(),
public function messages(), and
public function authorize()

但是,前端需要显示以下数据:    title(与验证错误消息相关的标题),description(这是实际验证错误消息)和status(=红色,黄色等)

如何实际自定义请求的响应?

这样的事情似乎不起作用:

protected function  failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
        {
            $response = new Response(['data' => [],
                'meta' => [
                    'title' => 'Email Invalid'
                    'description' => '(The error message as being returned right now)',
                    'status' => 'red'
                ]);

            throw new ValidationException($validator, $response);

    }

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式在laravel中发出请求来执行此操作:

php artisan make:请求FailedValidationRequest

此命令将在

中创建名为FailedValidationRequest的类

App \ Http \ Request目录,您可以在此类中编写规则,如下所示:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FailedValidationRequest extends FormRequest
{
/**
 * 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 [
       'title' => 'required'
       'description' => 'required',
       'status' => 'required|numeric'
    ];
}

}

如果您想自定义错误消息,可以使用composer从此链接下载所需的语言: https://packagist.org/packages/caouecs/laravel-lang

并通过将languge folwder复制到资源文件夹中的lang目录来编写所需的语言。

'custom' => [
    'title' => [
        'required' => 'your custom message goes here',
    ],
 'decription' => [
        'required' => 'your custom message goes here',
    ],
   ],