我正在使用 Laravel 的验证器来验证控制器内的 JSON 请求:class InsertProduct extends ModuleApiController{ public function handle(Request $request, int $fileId) { $data = $request->json()->all(); $validator = Validator::make($data, [ 'products' => ['required', new ArrayWithType('seq', 'The :field field must be an array')], 'products.*' => ['required', new ArrayWithType('assoc', 'The :field field must be an object')], 'products.*.code' => 'required|alpha_num', 'products.*.variants' => ['required', new ArrayWithType('seq', 'The :field field must be an array')], 'products.*.variants.*' => ['required', new ArrayWithType('assoc', 'The :field field must be an object')], 'products.*.variants.*.barcode' => 'required|alpha_num', ]);字段products.*.code和products.*.variants.*.barcode字段可以是这样的:20032199231"AB3123-X""Z22.327p""001230572""Houston22"我似乎找不到接受所有这些潜在值但拒绝数组或对象(Laravel 解析 JSON 后的关联数组)值的规则。我尝试过的事情: Rule | Issue----------------------|--------------------------------------------------------------------'required' | Will validate JSON objects and arrays 'required|string' | Won't validate integer values like the first one above'required|alpha_num' | Won't validate the middle three values above'required|alpha_dash' | Won't validate values that contain periods (.) like the third one我需要的是类似的东西:'required|not_array'或者'required|scalar'但我在文档中找不到类似的东西。我真的需要为此编写自定义验证规则吗?
2 回答
月关宝盒
TA贡献1772条经验 获得超5个赞
你尝试过做这样的事情吗?使用is_scalar
$validator = Validator::make($request->all(), [
'products.*.code' => [
'required',
function ($attribute, $value, $fail) {
if (!is_scalar($value)) {
$fail($attribute.' isnt a scalar.');
}
},
],
]);
或者,如果您想注册自定义验证:
public function boot()
{
Validator::extend('is_scalar', function ($attribute, $value, $parameters, $validator) {
return !is_scalar($value);
});
}
进而:
$validator = Validator::make($request->all(), [
'products.*.code' => [
'required',
'is_scalar'
],
]);
- 2 回答
- 0 关注
- 85 浏览
添加回答
举报
0/150
提交
取消