首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用jquery验证以像素为单位添加验证维度?

问如何使用jquery验证以像素为单位添加验证维度?
EN

Stack Overflow用户
提问于 2017-11-29 07:47:22
回答 1查看 2.2K关注 0票数 2

我的jquery验证如下:

代码语言:javascript
复制
store: {
    rules: {
        banner: {
            required: true
        }
    },
    messages: {
        banner: 'The banner must be filled',
    },
    errorElement: 'span',
    errorPlacement: errorPlacement,
    highlight: highlight,
    unhighlight: unhighlight
},

如果用户没有上传尺寸为1170x300像素的横幅,则存在如下消息:

请上传一张尺寸为1170 x 300像素的图片。

我该怎么做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-29 07:53:13

您需要创建自定义验证方法。

代码语言:javascript
复制
$.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,如下所示

//文件是输入的id

代码语言:javascript
复制
<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);
    }
});

然后像这样打电话

代码语言:javascript
复制
rules: {
    banner: {
        dimention:[1170,300]
    }
}

工作小提琴链接琴杆

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47547534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档