Tuesday, May 18, 2010

JavaScript Validate file extension

How to validate upload file extension

Usage : Simple JavaScript for validate upload file extension. If you use this validation, user can't upload wrong file type.

Compatibility :




JavaScript Code :
Insert this JavaScript in the head section of the html code.

<script type="text/javascript">
function check_file_type(){
var file_name = document.getElementById('upload_file').value;
var file_extension = file_name.substring(file_name.lastIndexOf('.') + 1);

if(file_extension == "gif" || file_extension == "jpg") {
alert("Ok. This is valid file");
return true;
} else {
alert("Invalid File. File Format supported: JPJ and GIF Only");
return false;
}
return true;
}
</script>

Html Code :

<html>
<head>
<title>Check File Extension </title>
</head>

<body>
<input name="upload_file" id="upload_file" type="file" onchange="check_file_type();" />
</body>

</html>

Demo :





No comments: