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.
