首页 > 解决方案 > Laravel 验证:required_with 或 required_with_all 条件总是通过

问题描述

在这里发表了类似的帖子,但在我的情况下仍然不起作用。

$v = \Validator::make($keys, [
            'overall' => 'required',
            'taste' => 'sometimes|required_with_all:freshness, quantity, value',
            'freshness' => 'sometimes|required_with_all:taste, quantity, value',
            'quantity' => 'sometimes|required_with_all:taste, freshness, value',
            'value' => 'sometimes|required_with_all: taste, quantity, freshness'
        ]);

dd($v->fails()); //-> false should be true

我试图总结我在做什么:

我试图用“required_with”来做,但它不起作用。

我的示例数组是:

array:4 [
  "overall" => 0
  "freshness" => 1
  "quantity" => 2
  "value" => 3
]

缺少“味道”。

那么我做错了什么?

如果我完全理解文档:

required_with_all:foo,bar,...只有在所有其他指定字段都存在时,才必须存在正在验证的字段。

这意味着如果:

例如 'taste' => 'sometimes|required_with_all:freshness, quantity, value',表示当新鲜度、数量、值存在,而参数 'taste' 不存在时,就会发生验证错误。

但它不...

标签: laravellaravel-validation

解决方案


有时:字段只有在数据数组中存在时才会被验证。

由于taste未在您的示例数组中显示,因此无法验证。试试不sometimes

'taste' => 'required_with_all:freshness, quantity, value'


推荐阅读