ActionScript 3 Windows Filename Regexp

The project I’m working on today allows users to type their own filenames. The actual file extension is added afterwards by my system. I needed to check that the filename itself is valid for Windows so I came up with this:

var file_name:String = ” #DOG!”£$%^&*()_+{}~@:?><|¬`-=[]#’;/.,”;

// Remove chars not allowed in Windows filename / : * ? ” < > |
file_name = file_name.replace(/[~\/:*?”<>|]/g, “”);

// Trim leading and trailing whitespace.
file_name = file_name.replace(/^s+|s+$/gs, “”);

// traces #DOG!£$%^&()_+{}@¬`-=[]#’;.,
trace(file_name);

Although it looks like crap that is still a valid file name. So then my system automatically appends the custom file extension that I’m using. I’m clearly not a regexp wizard but the above seems to work for me. Could probably combine the two but I’m not fussed for now. I got the trim regexp from the comments in this post.

Another option would of been to use the TextFields restrict property which will prevent them from typing or pasting in any of the illegal characters. In hind-site I’ll probably switch to using that as it will be less confusing for the user:

this.my_textfield.restrict = “^\\/:*?”<>|”;

Comments: None so far...be the first!

Leave a reply

Your email address will not be published. Required fields are marked *

Victorious warriors win first and then go to war, while defeated warriors go to war first and then seek to win.

— Sun Tzu