【问题标题】:Laravel required_if and mimes not working on file inputLaravel required_if 和 mimes 不能处理文件输入
【发布时间】:2021-03-18 15:09:36
【问题描述】:

请求文件中的代码

public function rules()
{
    return [
        'type' =>'required|in:1,2',
        'add' => 'required_if:type,2|in:1,2',
        'image' => 'required_if:add,2|mimes:jpeg,jpg,png,webp|max:10000'
    ];
}

添加属性选择框有2个选项:

  1. 不要上传图片
  2. 上传图片

image 属性上我确实使用了 required_if add 属性的值为 2(即选项 2,我想添加图像),然后才使图像字段成为必填字段以及 mime 和最大文件大小验证。

但问题是,当从添加选择框中选择选项一时,这意味着我不想上传图片,然后用户提交表单,这会引发验证:
图片必须是以下类型的文件: jpeg、jpg、png、webp。
根据我的验证代码,它应该忽略它,因为只有在选择选项 2 时才需要它,那么为什么会抛出这个 mimes 验证错误。

【问题讨论】:

  • 您遇到了什么错误?你能添加一些控制器代码吗?
  • 上面的代码在我正在验证输入的请求文件中。
  • 我正在做的是仅当用户从选择框中选择上传图像“是”时才验证 img 文件。 But when upload img "no" option is selected the image validation throws The image must be a file of type: jpeg, jpg, png, webp validation error which belongs to mimes rule instead of ignoring it as the option value is "no"
  • 尝试在图像验证中在required_if 之前添加sometimes 然后尝试。
  • 我确实尝试过有时可以为空的相同问题

标签: php laravel laravel-7


【解决方案1】:

我认为你可以简单地在 required_if 之后添加 nullable

'cover'=>['required_if:can_upload_file,true','nullable','mimes:jpeg,jpg,png','max:5120']

【讨论】:

    【解决方案2】:

    添加此代码

     return [
        'image.*' => 'nullable',
        'image.required' => 'mimes:jpeg,jpg,png,webp|max:10000'
      ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 2017-03-31
      • 2022-12-08
      • 2015-12-27
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      相关资源
      最近更新 更多