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,

Link to comment
Share on other sites

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";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.