VeeValidate(vue.js) 图像文件大小和尺寸验证

VeeValidate(vue.js) image file size and dimensions validation

如何在 vue.js

中使用 vee validate 在这样的表单中设置验证

对于其中两个要求,有可用的 ("native") 条规则:

现在,

  • 图片尺寸小于小于500*500像素

...问题出在 less.

dimensions rule 测试 精确 大小。所以你需要调整它以测试小于或等于尺寸的尺寸。

一个简单的解决方案是从 official implementation of the dimensions rule 中获取代码并将其更改为测试 是否小于或等于

下面的演示就是这样做的。它创建为 maxdimensions:500,500 规则。

Vue.use(VeeValidate);

// based on https://github.com/baianat/vee-validate/blob/2.0.6/src/rules/dimensions.js
// and https://github.com/baianat/vee-validate/blob/2.0.6/locale/en.js#L18
const maxDimensionsRule = {
  getMessage(field, [width, height], data) {
      return (data && data.message) || `The ${field} field must be UP TO ${width} pixels by ${height} pixels.`;
  },
  validate(files, [width, height]) {
    const validateImage = (file, width, height) => {
    const URL = window.URL || window.webkitURL;
      return new Promise(resolve => {
        const image = new Image();
        image.onerror = () => resolve({ valid: false });
        image.onload = () => resolve({
          valid: image.width <= Number(width) && image.height <= Number(height) // only change from official rule
        });

        image.src = URL.createObjectURL(file);
      });
    };
    const list = [];
    for (let i = 0; i < files.length; i++) {
      // if file is not an image, reject.
      if (! /\.(jpg|svg|jpeg|png|bmp|gif)$/i.test(files[i].name)) {
        return false;
      }
      list.push(files[i]);
    }
    return Promise.all(list.map(file => validateImage(file, width, height)));
  }
};


new Vue({
  el: '#app',
  created() {
    this.$validator.extend('maxdimensions', maxDimensionsRule);
  }
})
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/vee-validate@latest/dist/vee-validate.js"></script>


<div id="app">
   <form role="form" class="row">      
        My File: <input name="My File" v-validate data-vv-rules="image|maxdimensions:500,500|size:100" type="file"><br>
        <span v-if="errors.has('My File')">{{ errors.first('My File') }}</span>
    </form>
</div>