Laravel 5.4 - 可以为零的必需参数的正确验证规则

Laravel 5.4 - Correct Validation rule for a required parameter that can be zero

我正在尝试验证将库存加载到 table 中的请求。到目前为止,库存始终为正值,并且以下验证规则完全符合预期:

[
    "value" => "required|integer|min:0"
]

库存已存储并且可以有多个值,现在 库存可以有一个 value 为零 (0),我认为它不适用于 'required'规则。

我已将其更改为使用 'present',我认为应该足够了,但它仍然失败,添加 'nullable' 也不起作用:

[
    "value" => "present|integer|min:0"
]

是否有验证规则来指定字段必须存在但值可以为零?

您的初始验证规则一直按预期运行; required 不会在 0 上引发错误:

[
    "value" => "required|integer|min:0"
]

来自Laravel documentation

The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

所以问题实际上出在我对 $request->intersect(...) 的使用上,因为它将值为零 (0) 的键视为 false,因此将它们从请求数据数组中删除。

对于可能遇到此问题的任何其他人,这里是将零 (0) 值视为真值的解决方案; null 值、空字符串和 false 将被视为 false。

Nb$params$rules$messagesarray。有关详细信息,请参阅 https://laravel.com/docs/5.4/validation#manually-creating-validators

return \Validator::make(array_filter($request->only($params), function($param) {
    // This is needed to strip out empty values but treat zero (0) as truthy (default array_filter behaviour is
    // to treat zero (0) as false) but we want these values to be present in the validated request data array as
    // zero (0) in the context of a denomination is valid now that we will hold unactivated stock in the Vault.
    return ($param !== null && $param !== false && $param !== '');
}), $rules, $messages);