4

FormRequest在我的应用程序中用于验证数据。

示例代码:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserRequest 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 [
            'skills' => "required|array",
            "skills.*" => "required|min:2|max:20"
        ];
    }
}

默认情况下,当我通过请求此示例数据时:

{
    "skills" => [
        "a",
        "apple"
    ]
}

然后得到错误信息:

{
    "errors": {
        "skills.0": [
            "The skills.0 must be at least 2 characters."
        ],

        "skills.1": [
            "The skills.1 may not be greater than 4 characters."
        ]
    }
}

我如何自定义此验证错误消息并在结果中得到类似这样的错误:

{
    "errors": {
        "skills": [
            "The skills with key 0 must be at least 2 characters.",
            "The skills with key 1 may not be greater than 4 characters."
        ]
    }
}
4

2 回答 2

-1

使用 Laravel表单请求验证。表单请求是包含验证逻辑的自定义请求类。

于 2020-09-07T04:50:32.077 回答
-1

您可以在表单请求中使用 messages() 方法自定义验证消息

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required' => 'A message is required',
    ];
}
于 2020-09-07T05:01:11.423 回答