我有一个文件输入框,验证不需要。但是如果输入框不为空,那么我想要执行文件类型和文件大小的验证。
jQuery(document).ready(function(){
jQuery.validator.addMethod("accept", function(value, element, param) {
return value.match(new RegExp("." + param + "$"));
});
jQuery.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
});
jQuery('#adminform').validate({
rules: {
resume: {
required: false,
accept: "(doc|docx|pdf)",
filesize: 1024 //1048576
}
},
......................
resume: {
accept: "File type not supported",
filesize: "File cannot be more than 1MB!"
},
现在的问题是,即使我没有提供任何输入并将其留空,我也会执行规则“接受”,即我收到消息“文件类型不是支持“即可。
答案 0 :(得分:0)
尝试此操作。不进行空检查可确保如果字段留空,则不会执行验证
$('input[type="file"]').on("change", function() {
if ($this.val() !== '') {
//do validation stuff here!!
}
});
答案 1 :(得分:0)
如果这有帮助,请尝试此操作:
$("#commentForm").validate({
rules: {
name: "required",
file: "required",
name: {
required: true,
minlength: 2
},
file: {
required: false,
minlength: 5
}
},
messages: {
name: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
file: {
required: "Please select a file",
minlength: "Your password must be at least 5 characters long"
}
},
submitHandler: function(form) {
if ($('#cfile').val() != "") {
$("#commentForm").validate({
rules: {
file: "required",
file: {
required: true,
minlength: 5
}
},
messages: {
file: {
required: "Please select a file"
}
}
});
$(form).submit();
} else {
alert('file missing.');
}
}
});