【问题标题】:Laravel 5.4 required if validation issue如果验证问题需要 Laravel 5.4
【发布时间】:2017-08-13 09:17:49
【问题描述】:

我有 2 个字段,accepts_usd 和 price_usd。

对于价格美元,我有一个验证规则:

'price_usd'=>'integer|required_if:accepts_usd,1',

对于accepts_usd:

'accepts_usd'=>'boolean|required',

当我想存储数据时,如果我将 accept_usd 设置为 false,它仍然会询问 price_usd。

这里有什么问题?我做错了什么?

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.4


    【解决方案1】:

    来自 laravel 文档: required_if:anotherfield,value,...

    如果 anotherfield 字段等于任何值,则验证中的字段必须存在且不为空。

    值不是实际值,它是另一个验证规则。

    【讨论】:

      【解决方案2】:

      您需要将代码更改为

      'price_usd'=>'integer|required_if:accepts_usd,==,1',
      

      【讨论】:

        【解决方案3】:

        试试'price_usd'=>'integer|required_if:accepts_usd,==,1',

        laravel docs 中所述:

        required_if:anotherfield,value,...

        验证中的字段必须存在且不为空,如果 anotherfield 字段等于任何值。

        【讨论】:

          【解决方案4】:

          我在 Laravel 8 中遇到了同样的问题。所以我添加了如下验证规则。

          $validated = $request->validate([
              'name' => ['required', 'min:3', 'max:255'],
              'is_public_template' => 'boolean',
          
              'logo' => ['bail', 'nullable', 'required_if:is_public_template,true', 'image', 'mimes:jpeg,bmp,png,jpg'],
              'public_template_name' => ['bail', 'nullable', 'required_if:is_public_template,true', 'min:3', 'max:255'],
              'description' => ['bail', 'nullable', 'required_if:is_public_template,true', 'min:8', 'max:255'],
              'active' => 'boolean',
          ]); 
          

          在我的例子中,is_public_template 是一个布尔类型,所以我在required_if 前面添加了bailnullable 规则。

          所以它工作正常。

          旁注:-您还应该转换布尔字段的值,否则它们将作为普通字符串返回,如“1”或“0”。

          【讨论】:

            猜你喜欢
            • 2017-07-12
            • 2017-11-20
            • 1970-01-01
            • 1970-01-01
            • 2016-12-18
            • 2019-05-18
            • 1970-01-01
            • 2017-09-08
            • 2017-10-13
            相关资源
            最近更新 更多