我正在使用 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 關注
- 115 瀏覽
添加回答
舉報
0/150
提交
取消