【发布时间】:2018-08-13 07:31:08
【问题描述】:
这是使用 jquery 验证插件进行图像验证的完整代码。维度和文件大小不是jQuery验证插件的方法。这些方法是使用 jquery validator.addMethod 方法从外部添加的功能。此代码用于验证在用户端(客户端)的图像。如何在提交按钮之前检查输入类型文件的图像验证意味着当用户选择图像时,验证是检查图像是否按照规则有效。
$('#image_form').validate({
rules: {
image: {
required: true,
extension: "jpg|jpeg",
dimension: [300, 300],
filesize: 50000
},
},
messages: {
filesize: "File is too large",
},
submitHandler: function (form) {
$('.spinner')
.css("display", "block");
form.submit();
}
});
$.validator.addMethod('filesize', function (value, element, arg) {
var minsize = 0;
if ((element.files[0].size > minsize) && (element.files[0].size <= arg)) {
return true;
} else {
return false;
}
}, "File size must be less than 500KB.");
//check image height and witdh at client side
$.validator.addMethod('dimension', function (value, element, param) {
if (element.files.length == 0) {
return true;
}
var width = $(element)
.data('imageWidth');
var height = $(element)
.data('imageHeight');
if (width < param[0] && height < param[1]) {
return true;
} else {
return false;
}
}, 'File resolution should be in 300X300.');
//remove the image attribute height and width
$('#input-file-now')
.change(function () {
$('#input-file-now')
.removeData('imageWidth');
$('#input-file-now')
.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;
console.log(width);
$('#input-file-now')
.data('imageWidth', width);
$('#input-file-now')
.data('imageHeight', height);
}
});
<form method="post" action="upload.php" id="image_form" enctype="multipart/form-data">
<input id="input-file-now" name="image" class="file-img" type="file">
<label id="custom_error" style="display:none;color:red">File resolution should be in 300X300.</label>
<button type="submit" class="btn btn-default btn1_sign ">Submit</button>
</form>
【问题讨论】:
-
验证器不起作用吗?
-
验证器有效,但不适用于图像选择。它适用于提交按钮。 @亚历克斯
标签: javascript jquery html