使用Laravel和Vue进行图像表单验证

huangapple go评论70阅读模式
英文:

Image form validation with Laravel and Vue

问题

I have an image field that should not be required, but should be limited to possible file types.
但是,如果我验证 MIME 类型,提交表单时没有图像是不起作用的。

request()->validate([
   'name' => ['required'],
   'type' => ['required'],
   'master_id' => ['required'],
   'description' => ['required'],
   'whom_id' => ['required'],
   'short_description' => ['required'],
   'image' => ['mimes:jpg,bmp,png', 'max:3072'],
]);
if (request()->image) {
    $ext = request()->file('image')->extension();
    $path = request()->file('image')->storeAs('image', $course->id . 'mainImage.' . $ext);
    $course->image = $path;
}

使用Laravel和Vue进行图像表单验证

英文:

I have an image field that should not be required, but should be limited to possible file types
But, if I validate mimes, submitting the form without an image does not work

request()->validate([
       'name' => ['required'],'name' => ['required'],
       'type' => ['required'],'master_id' => ['required'],
       'description' => ['required'],
       'whom_id' => ['required'], 'short_description' => ['required'],
       'image' => ['mimes:jpg,bmp,png','max:3072'],
        ]);
if(request()->image){
        $ext = request()->file('image')->extension();//Получение расширения файла
        $path = request()->file('image')->storeAs('image', $course->id.'mainImage.'.$ext);
        $course->image = $path;
 }

使用Laravel和Vue进行图像表单验证

答案1

得分: 2

通常情况下,对于标准表单提交,答案是有时,然而,您正在通过Vue进行提交,因此需要nullable

'image' => ['nullable', 'mimes:jpg,bmp,png', 'max:3072'],

请注意可选字段的说明

英文:

Normally for standard form submits, the answer is sometimes, however you're submitting by Vue, so it required nullable.

    'image' => ['nullable', 'mimes:jpg,bmp,png','max:3072'],

Mind the Note On Optional Fields.

huangapple
  • 本文由 发表于 2023年7月18日 14:17:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定