这是使用jquery验证插件进行图像验证的完整代码。尺寸和文件大小不是jquery验证插件的方法。这些方法是使用jquery validateator.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>
答案 0 :(得分:0)
就我而言:用户选择文件后;我验证文件格式和文件大小。如果没有,输入文件将为空。
请参见以下代码
function fileIsValid(fileName)
{
var ext = fileName.match(/\.([^\.]+)$/)[1];
ext = ext.toLowerCase();
var isValid = true;
switch(ext)
{
case 'png':
case 'jpeg':
case 'jpg':
case 'tiff':
case 'gif':
case 'tif':
case 'pdf':
break;
default:
this.value='';
isValid = false;
}
return isValid;
}
function VerifyFileNameAndFileSize(){
var file = document.getElementById('GetFile').files[0];
if(file != null){
var fileName = file.name;
if(fileIsValid(fileName) == false){
alert('error->format');
document.getElementById('GetFile').value = null;
return false;
}
var content;
var size = file.size;
if( (size != null) && ((size/(1024*1024)) > 3)){
alert('size');
document.getElementById('GetFile').value = null;
return false;
}
return true;
}
else
return false;
}
<input type="file" id="GetFile" onchange="VerifyFileNameAndFileSize();" accept=".pdf,.png,.gif,.jpeg,.tiff,.jpg"/>