You need to iterate over
the files
collection[
^], in browsers that support it.
(Browsers that don't support it[^] don't support multiple file selection either.)
function checkSingleFileExtension(fileName, validExtensions) {
var index = fileName.lastIndexOf('.');
if (index == -1) {
alert('All files must have an extension.');
return false;
}
var ext = fileName.substr(index + 1).toLowerCase();
for (var index = 0; index < validExtensions.length; index++) {
if (ext === validExtensions[index]) {
return true;
}
}
alert('The file extension ' + ext.toUpperCase() + ' is not allowed.');
return false;
}
function checkFileExtension(elem) {
var validExtensions = ['doc', 'pdf'];
if (elem.files) {
for (var index = 0; index < elem.files.length; index++) {
var file = elem.files[index];
if (!checkSingleFileExtension(file.name, validExtensions)){
return false;
}
}
}
else {
if (!checkSingleFileExtension(elem.value, validExtensions)){
return false;
}
}
return true;
}
HOWEVER, be aware that not all operating systems use file extensions. Your code will only really work on Windows. You should really be using the
accept
attribute instead.
<input type="file"> - HTML | MDN :: Limiting accepted file types[
^]
Also, it's quite easy to turn off or otherwise bypass Javascript validation. Anything you validate on the client should also be validated on the server.