php – Laravel 5 – 根据需要验证数组,但允许传递一个空数组
发布时间:2020-12-14 19:38:22 所属栏目:大数据 来源:网络整理
导读:我正在使用验证器验证Laravel 5.4中的请求,请参阅文档: https://laravel.com/docs/5.4/validation#validating-arrays 基本上,这是Controller中的代码: public function createSomeResource(Request $request){ $this-validate($request,[ 'items' = 'requi
我正在使用验证器验证Laravel 5.4中的请求,请参阅文档:
https://laravel.com/docs/5.4/validation#validating-arrays 基本上,这是Controller中的代码: public function createSomeResource(Request $request) { $this->validate($request,[ 'items' => 'required',]; ... } 我想要求字段“items”的存在,并且这个代码可以实现,但问题是当“items”字段是空数组时验证失败,即 { "fields": [] } ,这是一种不受欢迎的行为.我知道这是“必需”参数的记录行为,但我没有看到任何“干净”的解决方法.我也尝试过: public function createSomeResource(Request $request) { $this->validate($request,[ 'items' => 'required_unless:items,[]',]; ... } 但它也失败了,可能是因为文档说它在“required_unless”子句之后适用于不同的字段,但我并不完全确定. 你能否建议我一种方法来要求存在字段“items”而不禁止空数组? 编辑:我想到的另一个“显而易见”的方法是使用“present | array”规则,它几乎可以实现我想要的,但不幸的是,一个空字符串也通过了验证规则,这可能是一个错误Laravel,也许不是 – 我在Laravel github存储库中为它开了一个问题:https://github.com/laravel/framework/issues/18948
试试这个:
public function createSomeResource(Request $request) { $this->validate($request,[ 'items' => 'present|array',]; ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |