【问题标题】:Laravel 9 the field must be a file even though I said it can be nullable (validation)Laravel 9 该字段必须是文件,即使我说它可以为空(验证)
【发布时间】:2022-08-18 04:32:31
【问题描述】:

我在验证类中有这个函数:

public function rules(): array {
    return [
        // ...
        \'content_image\'       => \'nullable|file|mimetypes:png|max:2000\',
        // ...

    ];
}

我声明,这可以为空,但如果不是,它必须是 PNG 文件,最大大小为 2mb\'s

似乎很简单:

来自 Api 调用的 FormData 请求:

content: <p>1</p>
content_image: null // => Should be allowed
live_wire_component: null
page_name: test-page
page_id: 27
order: 1

验证说不:

{
  \"content_image\": [
    \"The content image must be a file.\",
    \"Images can only be PNG\"
  ]
}

我 900% 确定这是通过验证允许字段为空的方式:

From the docs

可为空的

验证中的字段可能为空。

那么为什么即使我说它可以是空的,它也需要一个图像呢?

  • 尝试使用sometimes
  • 而不是 \'content_image\' => \'nullable|file|mimetypes:png|max:2000\',使用 \'content_image\' => [ \'nullable\', \'mimes:png\', \'最大值:2048\',],
  • 我知道它可能不适用于版本 9,但仅适用于 ccheck:stackoverflow.com/questions/53179046/…
  • @TimLewis 知道这一点.. 但是您可能没有体验到有区别,例如,当您将其用于正则表达式时.. 第一个会失败.. 所以.. 还有另一个区别.. 只是不需要使用 \'file\' 作为规则

标签: php laravel laravel-validation


【解决方案1】:

尝试使用上述https://laravel.com/docs/9.x/validation#validating-when-present 评论中所述的@SergheiLeonenco 有时规则 另请注意,我修改了“哑剧”

public function rules(): array {
    return [
        // ...
        'content_image'       => 'sometimes|file|mimes:png|max:2000',
        // ...

    ];
}

【讨论】:

    【解决方案2】:

    在您的请求验证中将 content_image 属性更改为此。

    'content_image'       => 'nullable|file|mime:png|max:2000',
    

    我希望它有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-30
      • 2019-01-22
      • 2018-05-20
      • 1970-01-01
      • 2015-03-08
      • 2015-08-07
      • 2015-03-21
      • 2020-10-23
      相关资源
      最近更新 更多