Friday, July 16, 2010

Restrict characters in input text field using AS3

Yeah, this is another tutorial about input fields :P
Say, you need to create a text field for phone numbers and you need to restrict every symbol but numbers. This question is asked alot, although the solution in Actionscript 3 is pretty simple:


The above code lets the user only write numbers in the field. Here's an example of using this method:



Anonymous said...

Is there a way to display a message if the user wants to enter a character that is not allowed?

Kirill Poletaev said...

Perhaps you could listen to the keyboard of the user and work with the key codes... For example, this script would trace "Bad symbol!" if the user hits anything that isn't a number:

if (event.keyCode < 48 || event.keyCode > 57)
trace("Bad symbol!");

codesignist said...

You can exclude chars like that:

exceptNumbers.restrict = "^0-9";

digital signatures said...

Good post.But is there a method which validate a phone number with javascript or any of the language.But the code should validate all international phones with there country code.Also note that this is more than restricting length to maximum and only digits

Kirill Poletaev said...

You could use regular expressions for that.

Anonymous said...

sir this is really helpful on the project i was currently working.. but how can i restrict the "-" character.. i need this so the user can input negative numbers.. thanks..

Anonymous said...

nvm my question sir.. i already come up with my own solution. thankyou

Sarah Northway said...
This comment has been removed by the author.
Sarah Northway said...

To include "-" (or "^") you need to escape it using double backslashes like "\\-". So this includes letters, numbers, underscore, space and dash:

textName.restrict="a-zA-Z0-9_ \\-"

Post a Comment