Max Value for TextInput in Flex
Does anyone know of a way to restrict a user from entering a number over 100 into a textinput field in flex?
i.e. a user can enter any number between and including 0-100 but not 101
Thanks in advance for 开发者_如何学编程any advice!
Try this, it should give you the results you're looking for - it won't allow you to enter anything out of range and will flag it as invalid (with a nifty tooltip message as well).
The default validator just provides a way to validate the input, but not restrict entry within a range. The restrict property allows single character matching (but not a range like you're needing.)
This uses them both and some events to handle it for you - very clean and easy to read / change that range as well...
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:s="library://ns.adobe.com/flex/spark" height="100%" width="100%">
<fx:Declarations>
<s:NumberValidator id="numberValidator" property="text"
minValue="0" maxValue="100"
source="{inputNumber}" trigger="{inputNumber}" triggerEvent="change"
valid ="inputNumber.toolTip=inputNumber.text;"
invalid ="inputNumber.text=inputNumber.toolTip;"/>
</fx:Declarations>
<s:TextInput id="inputNumber" restrict="0-9"/>
</s:Application>
P.s. It might seem like cheating using the tooltip as I have, but the validator will provide it's own tooltip automatically. If you don't like that, you can stick it in another static var - I did it this way because of the validator provided tool tip as stated above and to keep it clean.
you have to check it manually, if this is your code
<input change='_handleTextChanges(event)' />
and this is the callback
function _handleTextChanges(evt:Event):void{
var target:TextInput = evt.currentTarget as TextInput;
if(!target) return;
if(parseInt(target.text) > 100){
Alert.show("You can't enter a number grater than 100");
target.text = "100";
}
if(parseInt(target.text) < 0){
Alert.show("You can't enter a number smaller than 0");
target.text = "0";
}
}
I haven't tried it but it should work
A few options:
- Use a NumericStepper and specify the maximum property. With a custom spark skin you could even remove the up and down arrows to make it act like a TextInput.
- Listen for the keyUp or keyDown events and write your own validation to prevent the user from typing numbers greater than 100. You could tie this to a NumericValidator.
精彩评论