4

How to set validation in form like this using vee validate in vue.js

  • Image dimension less then 500*500 pixel

  • Image size less then 100kb

4

1 回答 1

12

对于其中两个要求,有可用的(“本机”)规则:

现在,对于

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

...问题在于less

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

一个简单的解决方案是从规则的官方实现中 dimensions获取代码并将其更改为测试是否小于或等于.

这就是下面的演示所做的。它作为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>

于 2018-03-20T02:35:56.117 回答