【问题标题】:Validation for form not checking partly验证表格未部分检查
【发布时间】:2019-11-09 19:17:22
【问题描述】:

我有一个 Laravel 程序,可以保存表单数据并上传几张图片。在验证中,有两个规则。图片是必需的,并且必须是图片类型(jpg、jpeg、png)。但是,验证只检查文件类型而不检查“必需”。即使没有图像,它也允许用户提交。为什么?

public function updateImages(Request $request, $id)
{
    $validatedData = $request->validate([
        'image' => 'required',
        'image.*' => 'image|mimes:jpeg,png,jpg|max:2048',
    ],
        [
            'image.*.image' => 'Format Error: Please uplaod image in a png or jpg format',
        ]);
    $item = Post::find($id);
    $existing_count = Photo::where('post', $item->id)->count();
    $countrequest = sizeof($request->file('image'));
    $count = $existing_count + $countrequest;
    if ($count >= 6) {
        return back()
            ->withInput()
            ->withErrors(['Only 5 images can be uploaded!']);
    }
    $upload = $this->imageUpload($item, $request);

    return redirect()->back()->with('message', 'Image Updated');
}

【问题讨论】:

  • 你为什么要image.*?为什么不把所有的验证放在image 下?

标签: laravel laravel-5.8


【解决方案1】:

使用 image.* 应用 require。例如-

image.*' => 'require|image|mimes:jpeg,png,jpg|max:2048', 

试试这个解决方案。它会起作用的。

【讨论】:

    【解决方案2】:

    您可以使用Laravel Request Validation

    创建表单请求类

    php artisan make:request ImageUpdateRequest
    

    去app/Http/Requests添加规则

    public function authorize()
    {
        return true;
    }
    
    public function rules()
    {
        return [
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
        ];
    }
    

    在你的控制器上

    use App\Http\Request\ImageUpdateRequest;
    
    public function updateImages(ImageUpdateRequest $request, $id)
    {
        $item = Post::find($id);
        $existing_count = Photo::where('post',$item->id)->count();
        $countrequest = sizeof($request->file('image'));
        $count= $existing_count+$countrequest;
        if ($count >= 6 ){
            return back()
            ->withInput()
            ->withErrors(['Only 5 images can be uploaded!']);
        }
        $upload = $this->imageUpload($item, $request);
        return redirect()->back()->with('message', 'Image Updated');
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 2011-07-29
      • 1970-01-01
      • 2012-11-02
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多