php - Laravel Validation 不会抛出真正错误的字段的错误
问题描述
我有一个验证块如下:
$this->validate($request, [
'id' => 'required|string|unique:user,id|max:32',
'email' => 'required|email|max:191',
'name' => 'nullable|string',
'birthDate' => 'nullable|date_format:Y-m-d',
'countryId' => 'nullable|integer',
'city' => 'nullable|string|max:191',
'address' => 'nullable|string',
'zipCode' => 'nullable|string|max:191',
'phone' => 'nullable|string',
]);
我正在发送这样的数据:
{
"id": "nJy8zWQ6VuptDFNA",
"email": "email@email.com",
"name": "name",
"birthDate": "1980-01-01",
"countryId": 1481,
"city": "a city",
"address": "this is an address",
"zipCode": "123400",
"phone": 09876554321
}
我将电话字段作为不正确的数据类型发送。然后响应就像电话字段类型错误。
但我得到了这样的回应:
{
"id": [
"The id field is required."
],
"email": [
"The email field is required."
]
}
我在这里找不到问题。
解决方案
问题是您没有发送有效的 JSON 正文。
这段代码:
$json = <<<JSON
{
"id": "nJy8zWQ6VuptDFNA",
"email": "email@email.com",
"name": "name",
"birthDate": "1980-01-01",
"countryId": 1481,
"city": "a city",
"address": "this is an address",
"zipCode": "123400",
"phone": 09876554321
}
JSON;
json_decode($json);
echo json_last_error();
将回显 4,它是JSON_ERROR_SYNTAX
表示语法错误的代码。
错误是数字不能在 JSON 中以 0 为前缀。这可能是因为在 JavaScript 中以 0 为前缀表示八进制数,但在 JSON 中允许这样做可能会损害可移植性。
不幸的是,PHP 内置 JSON 解析器的默认行为是在语法错误时返回 null 并且不说任何其他内容。
这可能是 Laravel 的一个想法,它允许验证整个输入的格式是否正确,作为验证的一部分,以确保我们有办法检查我们发送的内容是否正确。
推荐阅读
- javascript - 未返回复选框的值
- javascript - 是什么导致此 Vue 3 应用程序中 prop 错误的类型检查失败?
- python - 满足 if 语句后如何使 tkinter 消息框弹出?我如何让程序不断检查是否有人赢了。?
- nginx - NGINX 反向代理注入 CORS 标头
- windows - 如何打印竖线或竖线字符?
- python - Keras 没有验证数据集
- javascript - 如何摆脱 html 移动网站上的大空白块?
- python - Prolog 中的简单聊天机器人 - 将 python 转换为 prolog
- ios - SwiftUI - 显示警报
- java - 如何在 Android Service 中实现定时器