Tuesday, April 28, 2009

How to check upload file extension (JavaScript)

Before uploading a file it's a good idea to check for valid file extensions you want.
Even though you can easily bypass JavaScript validation by disabling JavaScript in the browser, you can prevent genuine user errors by implementing this code.


<html>
<head>
<title>Upload Check</title>
<script type="text/javascript">

function vali_type()
{
var id_value = document.getElementById('up').value;

if(id_value != '')
{
var valid_extensions = /(.jpg|.jpeg|.gif)$/i;
if(valid_extensions.test(id_value))
{
alert('OK');
}
else
{
alert('Invalid File')
}
}
}


</script>
</head>

<body>

<input type="file" name="up" id="up"
onBlur="vali_type()" />

</body>
</html>



var valid_extensions = /(.jpg|.jpeg|.gif)$/i;
Check for .jpg, .jpeg and .gif file extentions in the end of the string
| - OR
i - Case Insensitive
$ - END

15 comments:

  1. Thanks for sharing, it came in very handy for a file upload I was doing.

    ReplyDelete
  2. Thanks, it made my job very easy..:)

    Thank you so much...

    ReplyDelete
  3. Thanks, although I wonder why you have .test in this line?

    if(valid_extensions.test(id_value))

    where does it come from?

    ReplyDelete
  4. .test() is the method that used to do the regex validation.

    http://www.w3schools.com/jsref/jsref_regexp_test.asp

    ReplyDelete
  5. Thanks for sharing this information.

    ReplyDelete
  6. Hey what if there is a table instead of a text box and if we had to get the value from the columns how can we do it?

    ReplyDelete
  7. Hey there, this helped me with a similar problem, only 1 comment though, it should be /(\.jpg|\.jpeg|\.gif)$/i else it will return true if the filename contains jpg in the name, even if the extension is pdf or whatever :)

    ReplyDelete
  8. nice post. many thanks

    ReplyDelete
  9. thanks mate...nice one

    ReplyDelete
  10. $/i wats the purpose

    ReplyDelete