是否有Laravel验证规则来检查字段是否为标量



我正在使用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',但我在文档中找不到类似的东西。

我真的需要为此编写一个自定义验证规则吗?

你试过这样做吗?使用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'
],
]);

没有这样的内置验证规则。您需要创建一个自定义验证规则(请参阅文档(。使用regex规则(参见文档(来实现它。

相关内容

  • 没有找到相关文章

最新更新