我希望在此脚本中显示1MB错误消息而不是1024:
http://jsfiddle.net/tyaenm09/37/
使用带有filesize扩展名的jquery-validation插件。
我当然可以强制消息MAX FILE SIZE {0}
到MAX FILE SIZE 1MB
,但是如果我需要在允许不同文件大小的同一页面中实现第二个输入文件,则该消息需要是可变的。
答案 0 :(得分:2)
我会在这做两件事。
var maxBytes = 1024000;
console.log(filesize(maxBytes,{exponent:2,round:1}))

<script src="https://cdnjs.cloudflare.com/ajax/libs/filesize/3.5.11/filesize.min.js"></script>
&#13;
然后,您可以使用每个文件上载字段
传递适当的最大大小(再次,以字节为单位)
$(function(){
$.validator.addMethod('filesize', function (value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, function(size){
return "MAX SIZE " + filesize(size,{exponent:2,round:1});
});
$('#form').validate({
rules: {
firstname: {
minlength: 6,
required: true
},
file1: {
required: true,
filesize: 1000 * 1024,
},
file2: {
required: true,
filesize: 1000 * 512,
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'div',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/filesize/3.5.11/filesize.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form id="form">
<div>
<label>File1 (max 1Mb)</label>
<input name="file1" type="file" />
</div>
<div>
<label>File2 (max 0.5Mb)</label>
<input name="file2" type="file" />
</div>
<button type="submit">Submit</button>
</form>
&#13;