Reputation: 1055
I'd like to show 1MB error message instead 1024 in this script:
http://jsfiddle.net/tyaenm09/37/
Using jquery-validation plugin with filesize extension.
I can force message MAX FILE SIZE {0}
to MAX FILE SIZE 1MB
of course, but if i need to implement a second input file in the same page with a different filesize allowed, the message need to be variable.
Upvotes: 1
Views: 3503
Reputation: 136074
I would do 2 things here.
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>
Then, you could just pass the appropriate max size (again, in bytes) with each file upload field
$(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);
}
}
});
});
<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>
Upvotes: 2