dsa88886666
2018-06-20 15:06
浏览 906
已采纳

Laravel验证 - 数组字段,只允许两个中的一个,但都不是必需的

I'm using Laravel Form Request Validation to validate an array of objects, within each object we have two keys neverExpires and numberOfBillingCycles. Neither of these two keys are required, but if both have a value validation should fail as I only want to accept one or the other.

"addOns": {
    "add": [
        {
            "inheritedFromId": "EMEX1",
            "neverExpires": "false",
            "numberOfBillingCycles": "10"   
        },
        {
            "inheritedFromId": "EX1",
            "neverExpires": "true"
        },
        {
            "inheritedFromId": "EX2"
        }
    ]
},

So, in the first instance, because both neverExpires and numberOfBillingCycles have values it should fail validation. The second and third instances should pass as it only contains neverExpires or doesn't contain either.

I've tried creating a custom validator and passing in the two fields as parameters eg.addOns.add.*.neverExpires and addOns.add.*.numberOfBillingCycles but the problem is the parameter index is not set and I can't seem to find the array index within the custom rule to enable me to check the right array object values.

Hope this makes sense? Cheers in advance.

图片转代码服务由CSDN问答提供 功能建议

我正在使用Laravel表单请求验证来验证对象数组,在每个对象中我们有两个键 neverExpires numberOfBillingCycles 。 这两个键都不是必需的,但如果两个键都有值,则验证失败,因为我只想接受其中一个。

 “addOns”:{
“ 添加“:[
 {
”“inheritedFromId”:“EMEX1”,
“neverExpires”:“false”,
“numberOfBillingCycles”:“10”
},
 {
“inheritedFromId”:“  EX1“,
”neverExpires“:”true“
},
 {
”inheritedFromId“:”EX2“
} 
] 
},
   
  
 

因此,在第一个实例中,因为 neverExpires numberOfBillingCycles 都有值,所以它应该无法通过验证。 第二个和第三个实例应该通过,因为它只包含 neverExpires 或者不包含任何一个。

我尝试创建自定义验证器并将这两个字段作为参数传递,例如。 addOns.add。*。neverExpires addOns.add 。* .numberOfBillingCycles 但问题是没有设置参数索引,我似乎无法在自定义规则中找到数组索引,以使我能够检查正确的数组对象值。

希望这有意义吗? 提前干杯。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxu5845 2018-06-20 17:57
    已采纳

    As long as you're using >= Laravel 5.5 you could validate the each item in the add array rather than the individual attributes:

    public function rules()
    {
        return [
            'addOns.add.*' => [
                function ($attr, $value, $fail) {
                    if (array_has($value, ['inheritedFromId', 'numberOfBillingCycles'])) {
                        $fail('You can not have both');
                    }
                },
            ],
        ];
    }
    
    点赞 评论

相关推荐 更多相似问题