Reputation: 4029
So I am trying to validate file uploading before the file itself is uploaded and would like to check for two conditions - whether or not the file is smaller than 5mb and whether or not the file is in an image format.
This is how I am doing it at the moment:
<script>
$(document).ready(function () {
$('input[type=file]').change(function () {
var fileSize = this.files[0].size/1024/1024;
if (fileSize > 5) { alert("Please check the size of your image");
$(this).val('');
}
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only image files are supported. Please check the format of your file and try again.');
}
});
});
</script>
It works fine except that if the file is too big and it is removed, the alert for wrong file type fires too because the input has changed.
Is there any better way to get around this? I'd like to check both conditions without the user getting warned about file format if only the image size is wrong. Could I kill the second function if the first one is triggered?
Upvotes: 2
Views: 1577
Reputation: 2516
Here is what you can do, create and manage an array of errors, and use it at the end. Click run to see the demo
$(document).ready(function() {
$('input[type=file]').change(function() {
var file = this.files[0],
val = $(this).val().trim().toLowerCase();
if (!file || $(this).val() === "") { return; }
var fileSize = file.size / 1024 / 1024,
regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$"),
errors = [];
if (fileSize > 5) {
errors.push("Please check the size of your image");
}
if (!(regex.test(val))) {
errors.push('Only image files are supported. Please check the format of your file and try again.');
}
if (errors.length > 0) {
$(this).val('');
alert(errors.join('\r\n'));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" />
Upvotes: 2