Jump to content

Verifying the file extension that will be uploaded


NLCJ

Recommended Posts

Hello,

I got a HTML form where users can upload a file. Since these files can be pretty big (about 4-5GB) I thought I would let JavaScript verify it so they don't waste time for an error (ofcourse I still got a backend verification). What I did is: I added an onchange="verifyfile()" to the file part of the form. And I made (with the help of Google ;)) this JavaScript:

function verifyfile() {
var ext = $('#file').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['avi','mpg','mpeg','wmv','mov','vob','flv']) == 1) {
    document.getElementById('errorextension').style.display="none";
    document.getElementById('uploadbutton').style.display="block";
}else {
    document.getElementById('errorextension').style.display="block";
    document.getElementById('uploadbutton').style.display="none";
}
}

It works fine if I, e.g. start with an .avi file and after that I get a .rar file. First I don't get the error message, and after that I get the error message.

However, it doesn't work the other way around. If I first do a wrong extension the button disappears and the error comes up, but if I change it to the right extension nothing happens.

 

I'm kinda lost and new in JavaScript so...

 

Regards,

Check for != -1 inArray will return the position of the element it finds and -1 if it doesn't find anything. 

 


if($.inArray(ext, ['avi','mpg','mpeg','wmv','mov','vob','flv']) != -1) {
    document.getElementById('errorextension').style.display="none";
    document.getElementById('uploadbutton').style.display="block";
} else {
    document.getElementById('errorextension').style.display="block";
    document.getElementById('uploadbutton').style.display="none";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.