Flex: Text Input that accepts number only

Viewed 37755

Need a code that only accepts numbers. Upon inputting, the code must check if it is number, if not, it must remove the entered key or not enter it at all

8 Answers

I use somthing like

<s:TextInput id="textInput"
    restrict="0-9.\\-"
    change="onChangeNumberTextInput(event, 6)"/>

private function onChangeNumberTextInput(event:TextOperationEvent, precision:uint = 2):void
    {
        var strNumber:String = "";
        if (event.currentTarget is mx.controls.TextInput)
            strNumber = (event.currentTarget as mx.controls.TextInput).text;
        else if (event.currentTarget is spark.components.TextInput)
            strNumber = (event.currentTarget as spark.components.TextInput).text;
        else
            return;

        var ind:int = strNumber.indexOf(".");
        if (ind > -1)
        {
            var decimal:String = strNumber.substring(ind + 1);
            if (decimal.indexOf(".") > -1)
                strNumber = strNumber.substring(0, ind + 1 + decimal.indexOf("."));
            if (decimal.length > precision)
                strNumber = strNumber.substring(0, ind + 1 + precision);
        }

        if (event.currentTarget is mx.controls.TextInput)
            (event.currentTarget as mx.controls.TextInput).text = strNumber;
        else if (event.currentTarget is spark.components.TextInput)
            (event.currentTarget as spark.components.TextInput).text = strNumber;
    }

The change listener function removes everything beyond the number of precision characters from the decimal point, or any second occurrence of ".":

Related