在我的 Laravel 应用程序中,我试图验证我的请求正文,但一种特定情况会引发 ValidationException。
我的代码如下所示:
public function updateData(Request $request){
try {
$validatedData = $request->validate([
'ids' => ['required', 'array'],
'ids.*' => 'integer'
]);
catch (ValidationException $th) {
return response()->json($this->createFailedResult($th->errors()));
}
}
我传递的数据如下所示:
没有异常(exception):
{
ids: [1]
}
有异常(exception):
{
ids: []
}
这就是Ecception:
[ids] => Array ( [0] => The ids field is required. ) )
我读过关于用“present”交换“required”,但我不希望验证忽略空字符串。
谢谢你的帮助!
最佳答案
I've read about exchanging "required" with "present", but i dont want empty strings to be ignored by the validation.
present
验证规则需要该字段的存在。带有
present|array
的有效请求包含以下内容之一:{
"ids": []
}
{
"ids": [1, 2, 3]
}
如果验证规则是
required|array
,只有后者有效。通过使用
'ids.*' => 'integer'
扩展您的验证规则,您确保提供的输入(如果有)被验证为整数。因此,以下内容无效,即使 ids
字段是 present
:{
"ids": ["", "ipsum"]
}
关于php - Laravel:验证请求中的空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997989/