【问题标题】:Both fields can be empty but when filled only one required两个字段都可以为空,但填写时只需要一个
【发布时间】:2021-08-12 17:24:43
【问题描述】:

我正在 Laravel 中制作一页并使用表单请求进行验证。我在那个页面上有 2 个代码。

  1. 优惠券代码 2) 促销代码

我想设置条件,使这些代码可以为空,但填充时只需要一个。

我已经尝试过了,但没有得到正确的结果。

return [
            'coupon_code' => 'nullable|required_without:promo_code',
            'promo_code' => 'nullable|required_without:coupon_code'
        ];

【问题讨论】:

    标签: laravel validation laravel-formrequest


    【解决方案1】:

    根据您的描述,很明显您希望允许这三个输入对:

    1. coupon_code null,promo_code null
    2. coupon_code 值,promo_code null
    3. coupon_code null,promo_code 值

    强制执行这 3 对值中的任何一个都不需要任何验证规则。您可以将这两个规则都设置为可为空,并且没问题。

    但是从字里行间看,您似乎要求拒绝这个值对:

    1. coupon_code 值,promo_code 值

    如果是这种情况,那么不要使用required,而是使用prohibited_unless

      [
        'promo_code' => [
          'prohibited_unless:coupon_code,null',
        ],
        'coupon_code' => [
          'prohibited_unless:promo_code,null',
        ],
      ]
    

    这假设您有默认的 ConvertEmptyStringsToNull 中间件。

    【讨论】:

    • 谢谢。它完全按照我想要的方式工作。
    【解决方案2】:

    使用required if 的验证。

    return [
                'coupon_code' => 'nullable|required_if:promo_code,==,null',
                'promo_code' => 'nullable|required_if:coupon_code,==,null'
            ];
    

    【讨论】:

    • 感谢您的回答,但使用此我不能将两个字段都设为空。我想设置一个条件,在该条件下我也可以将两个字段都设为 null。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 2013-08-06
    • 2020-04-19
    相关资源
    最近更新 更多