如何使用vue.js中的vee validate
以这样的形式设置验证图片尺寸小于500 * 500像素
图片尺寸小于100kb
答案 0 :(得分:5)
对于其中两个要求,有可用的(“原生”)规则:
image
rule。size:100
rule。现在,对于
......问题在于 less 。
{strong>完全尺寸的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>