Using the ZipCodeValidator class to validate US or Canadian zip codes

by Peter deHaan on August 25, 2007

in Validators, ZipCodeValidator, ZipCodeValidatorDomainType

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.

{ 3 comments… read them below or add one }

1 Leen Toelen August 27, 2007 at 2:24 pm

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

Reply

2 peterd August 27, 2007 at 10:04 pm

Leen,

Yes, you can use Validators with data models. For more information, see “Using validators with a data model” in the Adobe Flex 2.0.1 LiveDocs.

Peter

Reply

3 Rick May 14, 2009 at 11:18 am

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!

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: