Pages

Thursday, 29 March 2012

Validators and Formatters example with Area Code Lookup in flex

Validators

  • Validators can be used to verify that data meets certain criteria on the client before being sent to the server.
  • Validation occurs when the field loses focus
  • Error message is displayed on mouseover
  • Indicate the source and source property, for example, mx:TextInput/text.



Formatters

  • Formatters are used to automate data formatting tasks to produce a meaningful display of information from raw data.
  • Triggered by calling the formatter's format() method.

ValidatorsandFormattersExampleWithAreaCodeLookup.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
 layout="vertical"
 backgroundAlpha="0" backgroundColor="#FFFFFF">

    <mx:HTTPService
        id="areacodeService"
        url="http://www.webservicex.net/uszip.asmx/GetInfoByAreaCode"
        resultFormat="e4x"
    />

    <mx:Script>
        <![CDATA[
            public function requestAreacode():void {
                areacodeService.cancel();
                var params:Object = new Object();
                params.USAreaCode = code.text;
                areacodeService.send(params);
            }
        ]]>
    </mx:Script>

    <mx:PhoneNumberValidator source="{phone}" property="text" />
    <mx:PhoneFormatter id="phoneFormatter" formatString="###.###.####" />

    <mx:Form>
        <mx:FormItem label="Enter a phone number.  Characters allowed: ()-.+ and space">
            <mx:TextInput id="phone" />
            <mx:Button label="Lookup Area Code" click="requestAreacode();"/>
        </mx:FormItem>

        <mx:FormItem label="Stripped phone number">
            <mx:Text id="stripped_phone" text="{phone.text.replace(/\D/g, '')}" />
        </mx:FormItem>

        <mx:FormItem label="Formatted phone number">
            <mx:Text text="{phoneFormatter.format(stripped_phone.text)}" />
        </mx:FormItem>

        <mx:FormItem label="Area Code">
            <mx:Text id="code" text="{stripped_phone.text.substr(0,3)}" />
        </mx:FormItem>
    </mx:Form>

    <mx:DataGrid dataProvider="{areacodeService.lastResult.Table}">
        <mx:columns>
            <mx:DataGridColumn headerText="City" dataField="CITY" />
            <mx:DataGridColumn headerText="State" dataField="STATE" />
            <mx:DataGridColumn headerText="Zip" dataField="ZIP" />
            <mx:DataGridColumn headerText="Area Code" dataField="AREA_CODE" />
            <mx:DataGridColumn headerText="Time Zone" dataField="TIME_ZONE" />
        </mx:columns>
    </mx:DataGrid>

    <mx:TextArea id="resultFld" text="{areacodeService.lastResult}" width="400" height="152"/>

</mx:Application>

Rendered Example

No comments:

Post a Comment