Sunday, July 10, 2011

Using the ZipCodeValidator class to validate US or Canadian zip codes

The following example shows how you can use the ZipCodeValidator to validate either US or Canadian zip codes (or should that be “postal codes” for our friends from the Great White North?). It turns out that making the ZipCodeValidator “Canadian friendly” is as simple as setting the domain property, and passing a constant value from the ZipCodeValidatorDomainType class (valid constants are US_ONLY and US_OR_CANADA).
Full code after the jump.
View MXML
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/25/using-the-
zipcodevalidator-class-to-validate-us-or-canadian-zip-codes/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.validators.ZipCodeValidatorDomainType;
        ]]>
    </mx:Script>

    <mx:ZipCodeValidator id="zipCodeValidator"
            source="{zipCode}"
            domain="{ZipCodeValidatorDomainType.US_OR_CANADA}"
            property="text"
            trigger="{button}"
            triggerEvent="click" />

    <mx:Form>
        <mx:FormHeading label="Enter shipping zip code" />
        <mx:FormItem label="Zip code:">
            <mx:TextInput id="zipCode" maxChars="10" />
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button id="button" label="Validate" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>

No comments:

Post a Comment