Search This Blog

2009-04-14

Validating Numbers in Flex

The following example shows how you can prevent or allow negative numbers when using the NumberValidator class by setting the Boolean allowNegative property

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/31/validating-negative-numbers-using-the-numbervalidator-in-flex/ -->
<mx:Application name="NumberValidator_allowNegative_test"
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">

<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.ValidationResultEvent;

private function numberValidator_invalid(evt:ValidationResultEvent):void {
Alert.show(evt.message);
}

private function numberValidator_valid(evt:ValidationResultEvent):void {
Alert.show(evt.type);
}
]]>
</mx:Script>

<mx:ApplicationControlBar dock="true">
<mx:Form styleName="plain">
<mx:FormItem label="allowNegative:">
<mx:CheckBox id="checkBox"
selected="true" />
</mx:FormItem>
</mx:Form>
</mx:ApplicationControlBar>

<mx:NumberValidator id="numberValidator"
allowNegative="{checkBox.selected}"
source="{textInput}"
property="text"
trigger="{button}"
triggerEvent="click"
invalid="numberValidator_invalid(event);"
valid="numberValidator_valid(event);" />

<mx:HBox defaultButton="{button}">
<mx:TextInput id="textInput"
restrict="0-9.-"
maxChars="10" />
<mx:Button id="button"
label="validate" />
</mx:HBox>

</mx:Application>

No comments: