jQuery验证文件上传 [英] jQuery Validate File Upload
问题描述
我正在尝试使用jQuery Validate验证HTML文件上传
I am trying to validate a HTML file upload using jQuery Validate
我发现我可以使用meta选项,例如:
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'}}" />
但是它似乎不起作用.无论如何,我都需要添加required
类.然后,文件类型检查当然也行不通.我需要做其他事情吗?
But it does not appear to work. I need to add the required
class anyways. Then the file type check will not work too of course. Do I need to do something additional?
推荐答案
如果您要使用jQuery的validate
检查文件的大小,则可以执行以下操作:
If you want to use jQuery's validate
to check the size of the file, you can do so by doing the following :
1-加载其他方法文件
1- load the additional methods file
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
2-添加自定义方法以验证文件大小
2- add a custom method to validate the file size
$.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-使用新添加的方法作为验证规则来验证您的输入:
3- use the newly added method as a validation rule to validate your input:
$('#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" }
});
注意:当您上传空白文件类型的文件时,使用接受"验证规则而不是扩展名"会导致MIME类型错误消息.
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.
这篇关于jQuery验证文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!