Created
July 26, 2018 07:07
-
-
Save mflisikowski/f80e15c4e5c8e267c049c3b5ac6e3a6b to your computer and use it in GitHub Desktop.
VeeValidate - Max Dimensions Rule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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