Well, I’ve had 15 minutes of spare time and I’ve come up with the following HTML.
This is a front-end checking, prior the file upload. If the client has JavaScript disabled it won’t work. My recommendation would be to double check it on the server.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2" />
<title>Test file name</title>
</head>
<body>
<script language="javascript" type="text/javascript">
// code from http://lawrence.ecorp.net/inet/samples/regexp-parse.php
function xtractFile(data){
data = data.replace(/^\s|\s$/g, "");
if (/\.\w+$/.test(data)) {
var m = data.match(/([^\/\\]+)\.(\w+)$/);
if (m)
return {filename: m[1], ext: m[2]};
else
return {filename: "", ext:""};
} else {
var m = data.match(/([^\/\\]+)$/);
if (m)
return {filename: m[1], ext: ""};
else
return {filename: "", ext:""};
}
}
function checkFileNames() {
var VALID_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
formInput = document.getElementById('ulFile');
fileName = formInput.value;
pathinfo = xtractFile(fileName);
testString = pathinfo.filename.toUpperCase()+pathinfo.ext.toUpperCase();
badName = false;
for (c = 0; c < testString.length; c++) {
if (VALID_CHARS.indexOf(testString[c]) < 0) {
badName = true;
break;
}
}
if (badName) {
alert('Invalid characters in file name! ('+pathinfo.filename+'.'+pathinfo.ext+')');
}
return !badName;
}
</script>
<form action="test.htm" onsubmit="return checkFileNames();" enctype="multipart/form-data" method="post">
<input type="file" name="ulFile" id="ulFile" />
<br /><br />
<input type="submit" value="Upload file" />
</form>
</body>
</html>
It’s a web form for file uploading. Sort of.
Select a file, on submitting the form validate the filename and extension to the VALID_CHARS string and off you go. Stop the submit for an invalid filename.
If you want to allow more characters in filename just add them to the constant VALID_CHARS. Use only UPPER CASE.
If you want to upload more files, iterate through the filenames.
If the filename string is empty nothing happens.
Feel free to expand/modify the code, I hope it helps as an example.