Use: Simple JavaScript to check file extention for a form with file upload feature, so that user does not upload the wrong file type
Compatibility: Tested on Internet Explorer(IE) 6.0 and Mozilla 1.6. Should work for IE4+ and Netscape 4+
Code:
if((document.form1.upload.value.lastIndexOf(".jpg")==-1) {
alert("Please upload only .jpg extention file");
return false;
}
Explain: lastIndexOf will return the index of the last occurrence of the specified search argument. If not found, -1 will return. More detail…


i could upload a file called “not.a.jpg.png” and it would work.
Ronin, you are right. Thanks
There is a better Javscript function at:
http://www.experts-exchange.com/Web/Web_Languages/ASP/Q_20895703.html
hola Liew.
esta bueno ese script pero me gustaria que coloques scripts como la de cargar un archivo e insertarlo en un campo blob de una base de datos
I don’t read spanish, here is translation of babelfish:
I assume you want me to write a file that upload the file and put in database? Sorry, javascript does not do that. You need to use PHP, ASP or other server side language.
I want a javascript to check for a valid CSV file and not just the extension. I mean if somebody renames any exe into CSV and tries to upload, the script should not allow.
hi ,
i think there is some small problem
because there ) missing. it is like this :
if((document.form1.upload.value.lastIndexOf(”.jpg”)==-1) {
but i think i must be like this ;
if((document.form1.upload.value.lastIndexOf(”.jpg”)==-1) ) {
isnt it ?
Hiiiii friends , I wanna know how to check the complete path browse in the file field in javascript ????
check is path is valid or not???
Nice JS .. but this will not work if the name is like file.jpg.zip
Here is better solution fom another site
function checkExt(formObj){
var filename = formObj.fileToUpload.value;
var filelength = parseInt(filename.length) – 3;
var fileext = filename.substring(filelength,filelength + 3);
// Check file extenstion
if (fileext != “gif” && fileext != “jpg”){
alert (“You can only upload gif or jpg images.”);
formObj.fileToUpload.focus();
return false;
}
formObj.submit();
}
Thanks
- http://www.PDFonFly.com
Your solution works, but:
When a file with the extention JPG or GIF is used, it does not pass the test… I have got this case on my website. A fix to your solution might be:
function checkExt(formObj){
var filename = formObj.fileToUpload.value;
var filelength = parseInt(filename.length) – 3;
var fileext = filename.substring(filelength,filelength + 3);
// Check file extenstion
if (fileext.toLowerCase() != “gif” && fileext.toLowerCase() != “jpg”){
alert (”You can only upload gif or jpg images.”);
formObj.fileToUpload.focus();
return false;
}
formObj.submit();
}
With this anything like
myphoto.JPG
myphoto.Jpg
Will be valid
Hope this can be of help to someone.