This is a useful JavaScript function which validates an image upload by checking the extension of the file that should be uploaded. If the extension is jpg, jpeg, png or gif it will return true. Otherwise, it will return false.
UPDATE This is a basic function to remind the users to upload an image with the right extension. You shouldn’t rely only on this method to validate an image upload as checking the MIME type in the backend (if, for instance, you’re using a scripting language such as PHP) is highly recommended. Backend validation is often a must and it applies to everything, not only file uploads.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Validate image on upload @ BitRepository.com</TITLE>
<META NAME="Author" CONTENT="Bit Repository">
<META NAME="Keywords" CONTENT="validate, extensions, file, javascript">
<META NAME="Description" CONTENT="A JavaScript Extension Validator for Images">
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate()
{
var extensions = new Array("jpg","jpeg","gif","png","bmp");
/*
// Alternative way to create the array
var extensions = new Array();
extensions[1] = "jpg";
extensions[0] = "jpeg";
extensions[2] = "gif";
extensions[3] = "png";
extensions[4] = "bmp";
*/
var image_file = document.form.image_file.value;
var image_length = document.form.image_file.value.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
return true;
}
}
alert("You must upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
return false;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<center>
<form name="form" action="http://www.microsoft.com" enctype="multipart/form-data" method="post" onSubmit="return validate();">
<h2>Validate image on upload</h2>
<br />
Upload an image: <INPUT type="file" name="image_file"> <input type="submit" name="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>
NOTE: You can add more extensions to the validator by continuing the extensions array.
Good luck!

