我的 jquery 验证如下:
store: {
rules: {
banner: {
required: true
}
},
messages: {
banner: 'The banner must be filled',
},
errorElement: 'span',
errorPlacement: errorPlacement,
highlight: highlight,
unhighlight: unhighlight
},
如果用户未上传尺寸为 1170 x 300 像素的横幅,则会出现如下消息:
Please upload an image with 1170 x 300 pixels dimension
我该怎么做?
最佳答案
您需要创建自定义验证方法
$.validator.addMethod('dimention', function(value, element, param) {
if(element.files.length == 0){
return true; <--- check here if file not added than return true for not check file dimention
}
var width = $(element).data('imageWidth');
var height = $(element).data('imageHeight');
if(width == param[0] && height == param[1]){
return true;
}else{
return false;
}
},'Please upload an image with 1170 x 300 pixels dimension');
并且您需要在图像更改时设置参数imageWidth和imageHeight,如下所示
// files is id of your input
<input type="file" id="files" name="name" />
$('#files').change(function() {
$('#files').removeData('imageWidth');
$('#files').removeData('imageHeight');
var file = this.files[0];
var tmpImg = new Image();
tmpImg.src=window.URL.createObjectURL( file );
tmpImg.onload = function() {
width = tmpImg.naturalWidth,
height = tmpImg.naturalHeight;
$('#files').data('imageWidth', width);
$('#files').data('imageHeight', height);
}
});
然后像这样调用
rules: {
banner: {
dimention:[1170,300]
}
}
工作 fiddle 链接 fiddle link
关于javascript - 如何使用 jquery 验证添加以像素为单位的验证尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47547534/