Checking file extension

Hello,

I have seen many Javascripts on Internet that checks the extension of the file before uploading. But all these scripts checks the extension when the Submit button is pressed. I want to check the file extension as soon as the file is selected. The script should delete the selected file from the type=file box and display an error message (when a file with the wrong extension is selected). Can any one point me in the right direction how to achieve this?

This is a crude lash-up that avoids alert boxes, which aren’t too refined for the job. The triggering point and auto deletion are browser dependent. This example expects an ‘.htm’ or ‘.html’ extension:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<title>Javascript Test</title>
</head>
<body>
<p>
<input type=file id='fs' ><span id='fWarn' style='color:#f00;font-weight:bold'></span>
<script type="text/javascript">

var fileBox = document.getElementById('fs');

fileBox.onblur = checkExt;

fileBox.onchange = function(){ this.onblur=null; checkExt(); }

function checkExt()
{   
 var warnBox = document.getElementById( 'fWarn' ), ext;
   
 if( /\\S/.test( fileBox.value ) && !/\\.html?$/i.test( fileBox.value ) )
 { 
  ext = fileBox.value.match(/\\.[^\\.]*$/) || "(none)" ;
  warnBox.innerHTML = 'Wrong file extension: ' + ext;
  fileBox.value = ''; 
 }
 else
  warnBox.innerHTML = '';
}

</script>
</body>
</html>