过修具有必填字段的非必需关联数组

我想要验证,如果我的请求包含一个关联数组类型的字段,则该数组需要包含特定字段(但仅当它存在)

ie,Array,如果存在,需要包含Foo:

{ data: {}}

{ data: { array: { foo: 1 } }

很好,但

{ data: { array: {} }

{ data: { array: { bar: 1 } }

不是。

I’ve written this validator:

['data.array' => 'sometimes', 'data.array.foo' => 'required']

But it doesn’t accept the first scenario.

>>> \Illuminate\Support\Facades\Validator::make(
   ['data' => []], 
   ['data.array' => 'sometimes', 'data.array.foo' => 'required']
)->errors()->all();
=> [
     "The data.array.foo field is required.",
   ]

I’d like to avoid using 'data.array.foo' => 'required_with:data.array'(当数组为空时,它也不适用于场景)

>>> \Illuminate\Support\Facades\Validator::make(
   ['data' => ['array' => []]], 
   ['data.array' => 'sometimes', 'data.array.foo' => 'required_with:data.array']
)->errors()->all();
=> []

还有任何非自定义验证器,可以帮助我完成此目的吗?

回答 1

  1. 赞同 2

    你也可以使用Rule::requiredIf在Laravel 5.6和Up,尝试一下:

    $validator =  Validator::make( $request->input(), [
        // ...
        'data.array.foo'=> Rule::requiredIf( function () use ($request){
            return (bool) $request->input('data.array');
        })
    ]);
    

    IBriahim-Dogan
    This works, however the validation is awkward and boils down to make data.array.foo required if data.array has any value.理想情况下,想要验证data.arrayPER两条规则data.array can be presentdata.array.foo is required but can admit that this might be the only way to accomplish what I'm after.