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

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.

  • 写回答

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');
                    }
                },
            ],
        ];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么