【问题标题】:Laravel 8 validation required_withoutLaravel 8 验证 required_without
【发布时间】:2022-01-19 08:58:11
【问题描述】:

我有三个领域

  • 标题
  • 身体
  • 图片[]

正文需要没有图像,所以我做了以下:

   $request->validate([
        'title' => 'required|string|max:' . (int) Setting::getValue('titlemaxchars'),
        'body'  => [
            'required_without:images',
            'string',
            'min:'.(int) Setting::getValue('postminchars'),
            'max:'.(int) Setting::getValue('postmaxchars'),
        ],
    ]);

    if ($request->hasFile('images')) {
        foreach ($request->file('images') as $file) {
            Validator::validate(['photo' => $file], [
                'photo' => ['required', 'file', 'image', 'max:2048'],
            ]);
        }
    }

问题在于:

  • body.string
  • body.min
  • body.max

如果有图像,我不希望他们发出任何错误消息,并且只有在没有图像时才会出现错误消息。

【问题讨论】:

  • 在正文中添加另一个验证字段nullable/sometimes 应该可以解决它
  • 我添加了 nullable 但即使没有图像@FarhanIbnWahid 也会使请求成功
  • 另一种猜测:required_without:images 将其更改为 required_without:images.*
  • 我试过了,但是不行。
  • 将字符串、最小值、最大值添加到正文中。当图像为空时

标签: laravel validation


【解决方案1】:

这对我有用!

 $request->validate([
        'title' => 'required|string|max:' . (int) Setting::getValue('titlemaxchars'),
    ]);

    if(!empty($request->hasFile('images'))){
        $request->validate([
            'body'  => 'nullable',
        ]);
    }else{
        $request->validate([
            'body'  => [
                'required',
                'string',
                'min:'.(int) Setting::getValue('postminchars'),
                'max:'.(int) Setting::getValue('postmaxchars'),
            ],
        ]);
    }

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 2018-08-15
    • 2021-12-09
    • 2021-03-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2020-11-20
    相关资源
    最近更新 更多