Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regex for filename validation 1

Status
Not open for further replies.

hererxnl

Technical User
Jul 8, 2003
239
US

I've been looking everywhere for a regex to validate a filename. Obviously this would disallow:
\ / : * ? " < > |

Someone must have this in their arsenal. Thanks in advance.

 
I'm not sure what the *exact* rules on filenames are anymore. Windows filenames don't nearly have the restrictions that they used to. Anyway, here's a regexp that disallows all the characters that you listed - additionally it will not allow multiple periods in a row (is that even valid?). Additionally, it requires the filename to have at least one period in it - which I know is not necessary. If you want to take that check out you can change the character marked in red to a *

This should cover most of your bases:
Code:
<script type="text/javascript">

function blah(str) {
   if (/^[^\\\/\:\*\?\"\<\>\|\.]+(\.[^\\\/\:\*\?\"\<\>\|\.]+)[!]+[/!]$/.test(str)) {
      alert("valid file name");
   }
   else {
      alert("this file name is invalid");
   }
}

</script>

<input type="text" id="txt" />
<input type="button" value="click me" onclick="blah(document.getElementById('txt').value)" />

-kaht

Looking for a puppy?

silky-icon-left.gif
[small]Silky Terriers are small, relatively odorless dogs that shed no fur and make great indoor pets.[/small]
silky-icon-right.gif
 

Thanks a bunch kaht, a star for your efforts.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top