8.7. Filtering Text Input

Problem

You want to restrict the characters that a user can type into an input field.

Solution

Set the restrict property of the text field.

Discussion

By default, a user can type any character into an input field. However, in many scenarios you might want to restrict the allowable characters. For example, you might restrict characters to numbers and dashes in the case of an input field for telephone numbers.

The TextField .restrict property lets you specify the allowed characters for user input in a field. Specify a string containing the allowable characters, such as:

myTextField.restrict = "abcdefg";

This example lets the user enter any of the following allowable characters: a, b, c, d, e, f, or g. Other characters are disallowed. If the user tries to enter “freedom”, only “feed” will appear, since the letters r, o, and m are not in the allowable character set.

Tip

If the restrict string is set to the empty string, then all characters are allowed. To prevent input entirely, set the text field’s type to “dynamic”.

Also note that ActionScript distinguishes between upper- and lowercase characters. In other words, there is a difference between a and A. If the restrict property is set to “abcdefg”, the uppercase variants of the allowable characters (such as A, B, C) will be entered as the lowercase (allowable) equivalents a, b, and c. The same is true in reverse: if a lowercase character is entered when only the uppercase counterpart is allowed, the character will ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.