Laravel 5-根据需要验证数组,但允许传递一个空数组 [英] Laravel 5 - validate array as required, but allow an empty array to be passed

查看:194
本文介绍了Laravel 5-根据需要验证数组,但允许传递一个空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用验证器在Laravel 5.4中验证请求,请参阅文档: https://laravel.com/docs/5.4/validation#validating-arrays

I'm validating a request in Laravel 5.4 with the validator, see the documentation: https://laravel.com/docs/5.4/validation#validating-arrays

基本上,这是控制器中的这段代码:

Basically, it's this code in the Controller:

public function createSomeResource(Request $request)
{
    $this->validate($request, [
        'items' => 'required',
    ];
    ...
}

我想要求字段"items"的存在,并且此代码可以做到这一点,但是问题是,当"items"字段为空数组(即

I would like to require the presence of the field "items" and this code does it, but the problem is that the validation fails when the "items" field is an empty array, i.e.

{
    "fields": []
}

,这是不希望的行为.我知道这是必需"参数的已记录行为,但是我看不到任何干净"解决方法.我也尝试过:

, which is an undesired behavior. I know that's the documented behavior of the "required" parameter but I don't see any "clean" workaround. I tried also:

public function createSomeResource(Request $request)
{
    $this->validate($request, [
        'items' => 'required_unless:items,[]',
    ];
    ...
}

,但是它也失败了,可能是因为文档说它在"required_unless"子句之后与另一个字段一起工作,但是我对此不太确定.

but it fails as well, probably because the documentation says that it works with a different field after the "required_unless" clause, but I'm not totally sure about it.

您能建议我一种方法来要求存在项目"字段而不禁止空数组吗?

Could you suggest me a way to require the presence of the field "items" without forbidding the empty array?

我想到的另一种显而易见"的方法是使用"present | array"规则,它几乎可以完成我想要的操作,但是不幸的是,空字符串也通过了该验证规则,这也许是Laravel中的错误,也许不是-我在Laravel github存储库上为其打开了一个问题: https://github.com/laravel/framework/issues/18948

another "obvious" approach that has come to my mind is to use the "present|array" rule and it almost does what I want, but unfortunately, an empty string passes that validation rule as well, which is maybe a bug in Laravel, maybe not - I opened an issue for it on the Laravel github repository: https://github.com/laravel/framework/issues/18948

推荐答案

尝试一下:

public function createSomeResource(Request $request)
{
    $this->validate($request, [
        'items' => 'present|array',
    ];
    ...
}

这篇关于Laravel 5-根据需要验证数组,但允许传递一个空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆