1

I got this jquery file type validation on the internet. It works great. I later added some code into it to validate file's size as well. But it did not raise alert box when my file size is greater than 50KB. I just learn jquery so I am not sure what i added is correct or not. Please help.

Here is JSFIDDLE

Here is the code:

<script>
$(document).ready(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(jpg|jpeg|gif)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Unsupported file');
} 
if ($(this).files.size > 50000 || $(this).files.fileSize > 50000)
    {
        //reset file upload control
       $(this).val('');
       //show an alert to the user
       alert('Allowed file size exceeded 50KB');


    }
}); });
</script>

This is what i have added into the existing code:

if ($(this).files.size > 50000 || $(this).files.fileSize > 50000)
    {
        //reset file upload control
       $(this).val('');
       //show an alert to the user
       alert('Allowed file size exceeded 50KB');


    }
Giang Nguyen
  • 495
  • 8
  • 22

2 Answers2

2

Working fiddle HERE

Code

$(document).ready(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(jpg|jpeg|gif)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Unsupported file');
} 
if (this.files[0].size > 50000 || this.files[0].size > 50000)
    {
        //reset file upload control
       $(this).val('');
       //show an alert to the user
       alert('Allowed file size exceeded 50KB');


    }
}); });

Fore more refer Here . It usesthis.files[0].size means get file size for 1st selectd file(If multiselect is enabled , checks for 1st image) ,anyway you are not having multiselect so you access it using 0th index of files selected because you can select only 1 file in regular operation.

Community
  • 1
  • 1
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
-1

$(document).ready(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(jpg|jpeg|gif)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Unsupported file');
} 
if (this.files[0].size > 50000)
    {
        //reset file upload control
       $(this).val('');
       //show an alert to the user
       alert('Allowed file size exceeded 50KB');


    }
}); });
<input type="file"/>