jQuery 验证文件上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6212946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Validate File Upload
提问by JM at Work
I am trying to validate a HTML file upload using jQuery Validate
我正在尝试使用 jQuery Validate 验证 HTML 文件上传
I found I can use the meta option like:
我发现我可以使用元选项,如:
$("#myform").validate({
meta: "validate"
})
<input type="file" name="upload" class="{validate:{required:true,accept:'docx?|pdf'}}" />
But it does not appear to work. I need to add the requiredclass anyways. Then the file type check will not work too of course. Do I need to do something additional?
但它似乎不起作用。required无论如何,我需要添加课程。那么文件类型检查当然也不起作用。我需要做一些额外的事情吗?
回答by Naoise Golden
If you want to use jQuery's validateto check the sizeof the file, you can do so by doing the following :
如果您想使用 jQueryvalidate来检查文件的大小,您可以通过执行以下操作:
1- load the additional methods file
1-加载附加方法文件
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
2- add a custom method to validate the file size
2- 添加自定义方法来验证文件大小
$.validator.addMethod('filesize', function(value, element, param) {
// param = size (in bytes)
// element = element to validate (<input>)
// value = value of the element (file name)
return this.optional(element) || (element.files[0].size <= param)
});
3- use the newly added method as a validation rule to validate your input:
3- 使用新添加的方法作为验证规则来验证您的输入:
$('#formid').validate({
rules: { inputimage: { required: true, extension: "png|jpe?g|gif", filesize: 1048576 }},
messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});
Note:using the "accept" validation rule instead of "extension" result in MIME type error messages when you upload a file with a blank file type.
注意:当您上传具有空白文件类型的文件时,使用“accept”验证规则而不是“extension”会导致 MIME 类型错误消息。
回答by PHPCoder
You can add a validation method to accomplish
您可以添加验证方法来完成
jQuery.validator.addMethod("uploadFile", function (val, element) {
var size = element.files[0].size;
console.log(size);
if (size > 1048576)// checks the file more than 1 MB
{
console.log("returning false");
return false;
} else {
console.log("returning true");
return true;
}
}, "File type error");
And Use it like this -
并像这样使用它 -
$(document).ready(function(){
$('#quote_form').validate({
rules: {
image: {
required: true,
extension:'jpe?g,png',
uploadFile:true,
}
}
});
});
I hope this will help you..
我希望这能帮到您..
回答by Pehmolelu
Have you read and tried it this way: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension?
您是否以这种方式阅读并尝试过:http: //docs.jquery.com/Plugins/Validation/Methods/accept#extension?
I mean rather than adding the validate rules to the class have you tried to just instantly add them in validate init?
我的意思是,您没有尝试将验证规则添加到类中,而是立即将它们添加到验证初始化中?

