Monday, August 10, 2009

Validating the image

In the Forms the mostly common task we use is uploading the image. When uploading the image we are in need of certain condition like we need only images to be uploaded or only the documents files to be uploaded.
For such type of requirements we need to provide the javascript code for restricting the users from uploading. This script will be validated at the client side so there is not burden on the server side. Hence makes the server work more easier.

Below is the javascript code for checking the uploaded image is image format or not and intern check whether the uploaded image format is jpg,gif or png format.

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


When ever you want to validate the file uploading control just copy this script and paste wherever you want to validate.If you want more formats you can add on the ext array.

The form is

<form name="form" action="http://test.com/test" enctype="multipart/form-data" method="post" onSubmit="return validate();">
<h2>Validate image on upload</h2>



Upload an image: <INPUT type="file" name="image_file"> <input type="submit" name="submit" value="Submit">

</form>

No comments:

Post a Comment