php - 如何自定义 laravel 数组验证错误键和消息
问题描述
我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."
]
}
}
解决方案
使用 Laravel表单请求验证。表单请求是包含验证逻辑的自定义请求类。
推荐阅读
- python - 元组内字典字典的封闭值
- pentaho - Pentaho - 在蒙德里安格式化日期
- apache-spark - 如何将小拼花文件合并到一个大拼花文件?
- angular - 嵌套服务中的 Angular 嵌套 observable - 如何
- hive - 在 apache hive 的维度表中具有代理键或 nk+effective_time 是否更好
- javascript - React 应用程序 - 在后台渲染提要
- kubernetes - coredns 容器在 kubernetes 工作节点中反复重启
- powershell - 如何从字符串中仅提取版本号
- linux - 仅删除文件名中至少包含一位数字的文件而不是目录
- c++ - 调用 mongocxx::instance 返回“mongoc: 无法初始化 OpenSSL”