Locking down input Textfields (AS3)

Huge disclaimer for this post: Messing with the default behaviour of text fields is a huge usability red flag. There are VERY few cases where this is acceptable, so use with caution.

Assuming you have a very good reason for needing to restrict which keys/characters can be entered into an input textfield, keep reading.

The super easy way: TextField.restrict
Pretty easy, just enter the characters or ACSII codes of either the keys you don’t want used or the keys you do want used. Check out the livedocs for the various combinations and syntax.

The pretty easy way: switch focus on Key events
Still pretty simple but a little more flexible if you only need to “block” a couple of keys. Basically, you add a listener for both the key down and key up events. If its the key you want to “block” that is down, you take focus away from the text field. Then, on key up, you put it back.

It’s easier to see in code:

package {
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.text.TextField;
import flash.text.TextFieldType;

public class TextFieldTest extends Sprite {

private var theTextField:TextField;
private var myCaretIndex:int;

public function TextFieldTest(){

theTextField = new TextField();
theTextField.type = TextFieldType.INPUT;
theTextField.border = true;
theTextField.width = 400;
theTextField.height = 30;
theTextField.multiline =false;

stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);

public function keyDownHandler( e:KeyboardEvent ):void {
// Keycode 8: backspace, Keycode 46: delete

if (e.keyCode == 8 || e.keyCode == 46) {

myCaretIndex = theTextField.caretIndex;
//Set the focus away from the textfield
stage.focus = null;


public function keyUpHandler( e:KeyboardEvent ):void {
if (e.keyCode == 8 || e.keyCode == 46) {
//set focus back on textfield and put the selection caret back
stage.focus = theTextField;
theTextField.setSelection(myCaretIndex, myCaretIndex);




Have a comment or question? Find me on twitter or email me.