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.

This is your last chance. After this, there is no turning back. You take the blue pill – the story ends, you wake up in your bed and believe whatever you want to believe. You take the red pill – you stay in Wonderland, and I show you how deep the rabbit hole goes. Remember; all I’m offering is the truth. Nothing more.

— Morpheus, The Matrix