Link to home
Start Free TrialLog in
Avatar of Neil2526
Neil2526

asked on

Javascript Regex filename validation

I am trying to weed out 'bad' characters when a user is creating a filename. I am doing so with Javascript. Below is my code, another set of eyes would be great.

I am always getting my else condition "This is an invalid..."

Thanks.
<form enctype='multipart/form-data' action='web_query2.php' method=POST name='web_query' onsubmit=\"return blah(document.getElementById('txt').value);\">
 
 
function blah(str) {
   if (/^[^\\\/\:\*\?\"\<\>\|\.]+(\.[^\\\/\:\*\?\"\<\>\|\.]+)+$/.test(str)) {
      alert(\"valid file name\");
      return true;
   }
   else {
     alert(\"This is an invalid filename, please try again!\");
     return false;
   }
}

Open in new window

Avatar of humanonomics
humanonomics
Flag of India image

I tried it using the attached code snippet and your method works like cool for me
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
 
<SCRIPT LANGUAGE='JAVASCRIPT'>
function blah(str) {
   if (/^[^\\\/\:\*\?\"\<\>\|\.]+(\.[^\\\/\:\*\?\"\<\>\|\.]+)+$/.test(str)) {
      alert("valid file name");
      return true;
   }
   else {
     alert("This is an invalid filename, please try again!");
     return false;
   }
}
</SCRIPT>
<BODY>
<form enctype='multipart/form-data' action='web_query2.php' method=POST name='web_query' >
 
<input type="button" name='submit' onclick='blah("abc.txt")'>
 
</form>
 
 
</BODY>
</HTML>

Open in new window

Avatar of David S.
Do you have a particular reason for not allowing multiple extensions? "archive.tar.gz" is an example of one.
Avatar of Neil2526
Neil2526

ASKER

Of course. The user is creating a csv data file.  
so why not also check for .csv ?
they are not creating the extension, only the filename.

ie:
       <th align=\"center\" class=\"fields\">
         <input type=\"text\" id=\"txt\" name=\"filename\">.csv
       </th>
human -

I tried your snipit, too and it works fine. I am still not hitting my first condition. I am always hitting my else clause. Attached is the full php file.
file.txt
Oww ok, so the input is only the file name without extension ?
yes. i think it has something to do with my regex.
But I used the same regex that you have used.
the regex checks for:

XXX.XXX

My form submits:

XXX

ie:
       <th align=\"center\" class=\"fields\">
         <input type=\"text\" id=\"txt\" name=\"filename\">.csv
       </th>

The user does not put in the DOT and the file extension.
ASKER CERTIFIED SOLUTION
Avatar of humanonomics
humanonomics
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial