• Author: nick
  • Published: Oct 23rd, 2009
  • Comments: 4

Flex - Regex restricted TextInput component

If you've ever used the `restrict` property on the Flex TextInput control - you've probably wished that it was more than just a string property. While it does allow you to specify characters, and character ranges like A-Z or 0-9, it isn't nearly as convenient or as robust as a regex.

Here is a simple subclass of TextInput that implements the same functionality as `restrict` but using a regular expression.

View the sample application ...and the source code.

 
package com.appdivision.components
{
    import flash.events.TextEvent;
    import mx.controls.TextInput;
 
    public class RegexTextInput extends TextInput
    {
 
        private var _regex:RegExp;
 
        public function RegexTextInput()
        {
            super();
        }
 
        [Bindable]
        public function set regex(value:RegExp):void
        {
            if (value != _regex)
            {
                _regex = value;
            }
        }
 
        public function get regex():RegExp
        {
            return _regex;
        }
 
        override protected function childrenCreated():void
        {
            super.childrenCreated()
 
            addEventListener(TextEvent.TEXT_INPUT, handleTextInput);
        }
 
        public function handleTextInput(event:TextEvent):void
        {
            if (regex)
            {
                 // What the text will be if this input is allowed to happen
                 var textToBe:String = "";
                // Accomidate for a selection
                if (selectionBeginIndex > 0)
                {
                    textToBe += text.substr(0, selectionBeginIndex)
                }
                textToBe += event.text;
                if (selectionEndIndex > 0)
                {
                    textToBe += text.substr(selectionEndIndex, text.length - selectionEndIndex);
                }
                var match:Object = regex.exec(textToBe);
                if (!match || match[0] != textToBe)
                {
                    // The textToBe didn't match the expression... stop the event
                    event.preventDefault();
                }
            }
        }
    }
}
 

Enjoy.

Tags: , ,

4 Responses to “Flex - Regex restricted TextInput component”


  1. James L.
    on Oct 24th, 2009
    @ 12:46 am

    So great! Just in time, I will use your code for my current project. Thanks.


  2. Mahesh
    on Nov 4th, 2009
    @ 10:44 pm

    excellent work, it has saved my time


  3. Vaishali
    on Nov 24th, 2009
    @ 10:18 pm

    Thanks a lot. Its great workaround to overcome limits of “restrict” attribute of TextInput.


  4. Shay
    on Jan 26th, 2010
    @ 9:29 am

    This is just what I need! I’m using this is a program I’m writing as part of my thesis project. I’ve included a comment in the package which references this URL as the source. Thanks!

Leave a Reply