.

.
JAVASCRIPT IMAGE EXTENSION VALIDATION

JAVASCRIPT IMAGE EXTENSION VALIDATION

Often forms require files to be uploaded by the end users, and the need arises to check the file type. Suppose we may restrict the users to select only images. This can be done using javascript or jquery.
Note: This script ensures whether the chosen file is of type jpg, png or gif.

<script type="text/javascript">
function check_upload(upload_field)
{    
var re_text = /\.jpg|\.png|\.gif/i;    
var filename = upload_field.value;
// Checking file type
if (filename.search(re_text) == -1)    
{        
alert("File does not have (jpg / gif / png) extension");
upload_field.value = '';
return false;    
}
return true;
}
 
function verify_upload()
{
if(document.upload_file.file1.value == "")
{
alert("Please select a file");
return false;
}
return true;
}
</script>

We can also use Jquery to validate the selected file on the fly.

<script type="text/javascript">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
$(".container").delegate("input[type=file]", "change", function(){
img_ext = $(this).val().split('.');
img_ext = img_ext[img_ext.length - 1];
if(img_ext != 'jpg' && img_ext != 'png' && img_ext != 'gif')
{
alert("File does not have (jpg / gif / png) extension");
$(this).val('');
}
});
});
</script>

The HTML Form

<div class="container">
<form enctype="multipart/form-data" method="post" action="" name="upload_file">
FILE: <input type="file" onchange="check_upload(this)" id="file" name="file1"><br>
ALT: <input type="text" name="alt" size="30" value="image" /><br>
<input type="submit" onclick="return verify_upload()" value="Upload" name="submit">
</form>
</div>