【问题标题】:Laravel Dynamically generated field validationLaravel 动态生成的字段验证
【发布时间】:2021-10-30 23:00:03
【问题描述】:

我有一个提交大量图片的表单,假设有 5 张图片。我将它们命名为 img1、img2..、img5。现在我正在一一验证这些字段。

我的验证码

$rules = [
            'image1' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:3072',
            'image2' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
            'image3' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
            'image4' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
            'image5' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
        ];

$msg = [
            'image1.required' => 'Image is required',
            'image1.image' => 'Please upload an Image for Image ',
            'image1.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image1.max' => 'Image size should be less than or equal 3MB',
            'image2.image' => 'Please upload an Image for Image ',
            'image2.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image2.max' => 'Image size should be less than or equal 3MB',
            'image3.image' => 'Please upload an Image for Image ',
            'image3.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image3.max' => 'Image size should be less than or equal 3MB',
            'image4.image' => 'Please upload an Image for Image ',
            'image4.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image4.max' => 'Image size should be less than or equal 3MB',
            'image5.image' => 'Please upload an Image for Image ',
            'image5.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image5.max' => 'Image size should be less than or equal 3MB',
        ];

$this->validate($req, $rules, $msg);

请告诉我是否有更好的方法来做到这一点? :)

【问题讨论】:

    标签: laravel laravel-8 laravel-validation


    【解决方案1】:

    使用数组代替文件名

    Laravel 多文件验证规则。

    $rule = ['image.*' => 'required|mimes:jpeg,png,jpg,gif,svg|max:3072'];
    $msg = ['image.*.image' => 'Please upload an Image for Image ',
            'image.*.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image.*.max' => 'Image size should be less than or equal 3MB'];
    

    【讨论】:

      【解决方案2】:

      你可以在一个数组 $images 中提交所有这些

      并进行验证:-

      $rules = [
      "images"   =>"required|array|min:1",
      "images.*" =>"required|image|mimes:jpeg,png,jpg,gif,svg|max:3072"
      ]
      

      除非你想更改 laravel 的默认验证消息,否则并不需要为每个验证设置消息

      【讨论】:

      • YHA 我真的想要自定义消息,但是如何使用普通的 HTML 表单发送数组?
      • <input type="file" name="image[]" multiple />
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多