简体   繁体   English

Laravel required_if 和 mimes 对文件输入不起作用

[英]Laravel required_if and mimes not working on file input

Code in request file请求文件中的代码

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'
    ];
}

The add attribute select box has 2 option:添加属性 select 框有 2 个选项:

  1. Don't upload image不要上传图片
  2. Upload image上传图片

On image attribute I did use required_if add attribute has value 2 (ie option 2, I want to add image) only then make image field to be a required field and mimes and max file size validation.图像属性上,我确实使用了 required_if添加属性的值为 2(即选项 2,我想添加图像),然后才使图像字段成为必填字段并进行 mimes 和最大文件大小验证。

But the problem is when option one is selected from add select box which mean I don't want to upload image and then user submit form this throws validation:但问题是当从添加 select 框中选择选项一时,这意味着我不想上传图像然后用户提交表单,这会引发验证:
The image must be a file of type: jpeg, jpg, png, webp.图片必须是以下类型的文件:jpeg、jpg、png、webp。
As per my validation code it should ignore it as it is required only if option 2 is selected then why this mimes validation error throws up.根据我的验证代码,它应该忽略它,因为只有在选择了选项 2 时才需要它,那么为什么会抛出这个 mimes 验证错误。

I think you can simply add nullable after required_if我认为您可以在 required_if 之后简单地添加 nullable

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

Add this code添加此代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM