Friday, March 7, 2008

How to restrict the Backslash(\) character

In ActionScript, if you want to restrict the characters that can be entered into a TextField (or TextInput), you use the restrict property. Check here for documentation.

For example, input_txt.restrict = "A-Z";
This restricts the characters to upperspace characters and disallows everything else.

And input_txt.restrict = "^0-9";
The ^ symbol indicates that whatever comes after that is disallowed. Here, the numbers 0 to 9 are not allowed, everything else is allowed.

The interesting part is what if you want to restrict the Backslash(\) character?

Apparently, the right way to do it is:
input_txt.restrict = "^\\\\";


From the livedocs documentation:
"You can use a backslash to enter a ^ or - verbatim. The accepted backslash sequences are \-, \^ or \\. The backslash must be an actual character in the string, so when specified in ActionScript, a double backslash must be used. "

So, the first two backslashes are as required, when you add the third backslash, the flex compiler thinks that you are trying to escape the " character. Hence you need the fourth backslash in the string.

Very interesting!