VeeValidate(vue.js) image file size and dimensions

2019-04-14 15:03发布

问题:

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

回答1:

For two of those requirements, there are available ("native") rules:

  • Must be an image, use image rule.
  • Image size less then 100kb, use size:100 rule.

Now, for the

  • Image dimension less than 500*500 pixels

...the problem is with the less.

The dimensions rule test for exact size. So you'll need to tweak it to test for size smaller than or equal to the size.

A simple solution would be to take the code from the official implementation of the dimensions rule and change it to test for smaller or equal to.

That's what the demo below does. It creates as maxdimensions:500,500 rule.

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>