【发布时间】:2022-01-20 13:31:47
【问题描述】:
我有以下验证规则,我需要确保streaming_platforms 数组包含正确的信息。因此,如果 enable 键为真,则需要 stream_key 和 stream_url。 stream_key 应该是一个字符串,stream_url 应该是一个 URL。
$validator = Validator::make($input, [
'name' => 'required|string|min:3|max:255',
'type' => 'required|in:private,public',
'streaming_platforms.*.stream_url' => 'required_if:streaming_platforms.*.enable,true|url',
'streaming_platforms.*.stream_key' => 'required_if:streaming_platforms.*.enable,true|string',
], [
'streaming_platforms.*.stream_url.required_if' => 'The stream url field is required when platform is enable.',
'streaming_platforms.*.stream_key.required_if' => 'The stream key field is required when platform is enable.',
]);
if ($validator->fails()) {
return $this->failResponse([
"message" => $validator->errors()->first(),
"messages" => $validator->errors(),
], 422);
}
一切正常,但即使 enable 值为 false,stream_url 和 stream_key 的 URL 和字符串验证规则也会触发。那么,如果没有应用required_if,为什么不停止检查下一个规则呢?
所以我尝试了以下数据。
{
"name":"testing",
"type":"public",
"streaming_platforms":[
{"id":16,"platform":"youtube","enable":true,"stream_url":"https://www.google.com","stream_key":"abdefghijk"},
{"id":17,"platform":"facebook","enable":false,"stream_url":null,"stream_key":null},
{"id":18,"platform":"custom","enable":false,"stream_url":null,"stream_key":null}
]
}
所以它返回
streaming_platforms.1.stream_url 格式无效。为了 Facebook 行。
我在某处读到您可以执行以下操作,即使用sometimes 规则。但我不知道如何处理数组类型的数据。
$validator = Validator::make($request->all(), [
'name' => ['required', 'min:3', 'max:255'],
'is_public_template' => 'boolean',
'logo' => ['required_if:is_public_template,true'],
]);
$validator->sometimes('logo', 'required|image|mimes:jpeg,bmp,png,jpg|dimensions:min_width=128,min_height=128', function ($input) {
return $input->is_public_template;
});
【问题讨论】:
-
您需要添加额外的可空/有时,因为即使其他条件不满足,默认情况下也会以某种方式设置所需的规则。另一个例子是
numeric规则,即使值为空也适用,因此要使其仅在该值存在时起作用,您还需要添加可空规则 -
nullable无法正常工作。 -
我预计问题是您的规则
required_if:streaming_platforms.*.enable,true表示 * 表示通配符,因此如果 任何 元素具有 enable:true 则将触发该规则。跨度> -
no miken 它是用于数组元素的。检查此链接。 laravel.com/docs/8.x/validation#validating-nested-array-input
标签: laravel laravel-validation