Skip to content

Instantly share code, notes, and snippets.

@mflisikowski
Created July 26, 2018 07:07
Show Gist options
  • Save mflisikowski/f80e15c4e5c8e267c049c3b5ac6e3a6b to your computer and use it in GitHub Desktop.
Save mflisikowski/f80e15c4e5c8e267c049c3b5ac6e3a6b to your computer and use it in GitHub Desktop.
VeeValidate - Max Dimensions Rule
import Vue from 'vue'
import pl from 'vee-validate/dist/locale/pl'
import VeeValidate, { Validator } from 'vee-validate'
import maxDimensionsRule from './maxDimensionsRule'
import Component from '@/components/Component.vue'
Validator.localize('pl', pl)
Vue.use(VeeValidate, {})
/* eslint-disable no-new */
new Vue({
$_veeValidate: {
validator: 'new'
},
el: '#app',
created() {
this.$validator.extend('maxdimensions', maxDimensionsRule);
},
render: h => h(Component)
})
// 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)));
}
};
module.exports = maxDimensionsRule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment