テキスト入力フィールド

by yun
♥0 | Line 63 | Modified 2010-09-08 10:51:10 | MIT License
play

ActionScript3 source code

/**
 * Copyright yun ( http://wonderfl.net/user/yun )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/c07X
 */

package {
    import flash.ui.Keyboard;
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFormat;
    import flash.events.FocusEvent;
    import flash.events.KeyboardEvent;
    public class MyTextField extends Sprite {
        public var fld:TextField;
        public var alertFld:TextField;
        public var minChars:uint = 8;
        public function MyTextField() {
            // テキストの書式
            var tf:TextFormat = new TextFormat();
            tf.font = "_sans";
            tf.size = 14;
            // テキスト入力フィールドの作成
            fld = new TextField();
            fld.type = TextFieldType.INPUT;
            fld.defaultTextFormat = tf;
            // 半角英数で16文字まで
            fld.restrict = "0-9a-zA-Z";
            fld.maxChars = 16;
            // 入力された文字を★印で表示
            fld.displayAsPassword = true;
            fld.x = 100;
            fld.y = 50;
            fld.width = 180;
            fld.height = 24;
            fld.border = true;
            addChild(fld);
            // 入力イベントを監視
            fld.addEventListener(FocusEvent.FOCUS_IN, focusInHandler);
            fld.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler);
            fld.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
            // 警告表示のテキストフィールドの作成
            alertFld = new TextField();
            alertFld.selectable = false;
            alertFld.background = true;
            alertFld.backgroundColor = 0xFAD163;
            alertFld.defaultTextFormat = tf;
            alertFld.autoSize = TextFieldAutoSize.LEFT;
            alertFld.text = "半角英数で" + minChars + "〜" + fld.maxChars + "文字を入力してください。";
            alertFld.x = fld.x;
            alertFld.y = fld.y + fld.height +2;
            alertFld.visible = false;
            addChild(alertFld);            
        }
        // 入力フィールドにフォーカスが入ったら注意書きを消す
        public function focusInHandler(event:FocusEvent):void {
            alertFld.visible = false;
        }
        // 入力フィールドのフォーカスが外れたら文字数をチェック
        public function focusOutHandler(event:FocusEvent):void {
            if (fld.text.length < minChars) {
                alertFld.visible = true;
            }
        }
        // 入力フィールドの中で改行キーが押されたら文字数をチェック
        public function keyDownHandler(event:KeyboardEvent):void {
            if (event.charCode == 13) {
                // 文字数がminCharsより少ないとき警告フィールドを表示
                if (fld.text.length < minChars) {
                    alertFld.visible = true;
                }
            } else {
                alertFld.visible = false;
            }
        }
    }
}