首页 > 解决方案 > 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."
    ]
}

我在这里找不到问题。

标签: phplaravelvalidation

解决方案


问题是您没有发送有效的 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 的一个想法,它允许验证整个输入的格式是否正确,作为验证的一部分,以确保我们有办法检查我们发送的内容是否正确。


推荐阅读