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>

View source is enabled in the following example.

5 thoughts on “Using the ZipCodeValidator class to validate US or Canadian zip codes

  1. Hi,

    is it possible to put validators on a model object, and tell the GUI to use these validators when validateall is triggered? I have some objects that are displayed in lots of forms, and centralizing the validator in one class make a lot more sense than putting them on each form seperately.

    Regards,
    Leen

  2. Isn’t it possible to use other domains then US/Canada? E.g. a dutch zipcode would be formatted like 0000 AA or 0000AA.

    Thanks!

Comments are closed.