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 = "^\\/:*?"<>|";
Share Article

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

Leave a reply

Please fill in the form fields and improve Skynet by completing the captcha!

Thank you! All comments are moderated so yours will appear shortly.

Children, gather round! No retreat, no surrender; that is Spartan lore. And by Spartan lore we will stand and fight… and die.

— King Leonidas, 300