22
Aug
07

Validating data using Regular Expressions

It looks like I forgot to post this and I’ve had this as a draft for a week. I was looking at creating a regular expression for validating a UPS tracking number and/or InfoNotice number and decided to do a quick RegExp for validating a Canadian postal code instead. Fear not, my 3 loyal readers, I’ll post the other regular expressions later on.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/22/validating-data-using-regular-expressions/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            private const postalcode_regex:RegExp = /^[A-Z][0-9][A-Z] [0-9][A-Z][0-9]$/i;

            private function validatePostalCode(evt:Event):void {
                if (postalcode_regex.test(ti1text)) {
                    ti1.errorString = null;
                } else {
                    ti1.errorString = postalCode_errorString;
                }
            }
        ]]>
    </mx:Script>

    <mx:String id="ti1text">{ti1.text}</mx:String>
    <mx:String id="postalCode_errorString">
        <![CDATA[Please enter a valid postal code in "L9L 9L9" format.]]>
    </mx:String>

    <mx:Form>
        <mx:FormItem label="Postal Code:" required="true">
            <mx:TextInput id="ti1"
                    maxChars="7"
                    restrict="A-Z 0-9"
                    change="validatePostalCode(event)" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>

View source is enabled in the following example.

As a keen reader, Peter J. Farrell, points out below, my RegExp is fairly inaccurate. But as long as you’re OK with that fact that Canadian Postal Codes won’t really be validated properly, here’s another trick… It turns out you can use POSIX style named classes in ActionScript 3.0 regular expressions.

var str:String = "Victoria, BC, Canada V8P 3A8";
var pattern:RegExp = /(?P<postalCode>[[:alpha:]][[:digit:]][[:alpha:]] [[:digit:]][[:alpha:]][[:digit:]])/ig;

trace(str.replace(pattern, "(postal)"));

var result:Object = pattern.exec(str);
trace("postal code: " + result.postalCode);

And because I can never find some good RegExp POSIX information easily (without looking up the information in Ben Forta’s “Regular Expressions in 10 Minutes” book), here’s the list of POSIX Character Classes for future reference:

[[:alnum:]] - The set of alpha-numeric characters (same as [a-zA-Z0-9]).
[[:alpha:]] - The set of alphabetic characters (same as [a-zA-Z]).
[[:blank:]] - Tab and space (same as [\t ]).
[[:cntrl:]] - The control characters (ASCII 0-31, and 127).
[[:digit:]] - Decimal digits (same as [0-9]).
[[:graph:]] - All printable characters except space (same as [[:print:]], except does not include space).
[[:lower:]] - Lower case letters (same as [a-z]).
[[:print:]] - The “printable” characters.
[[:punct:]] - Punctuation. Any character not in [[:alnum:]] or [[:cntrl:]] range.
[[:space:]] - Whitespace characters (same as [\f\n\r\t\v ]).
[[:upper:]] - Upper case letters (same as [A-Z]).
[[:xdigit:]] - Hexidecimal digits (same as [a-fA-F0-9]).


5 Responses to “Validating data using Regular Expressions”


  1. 1 Peter J. Farrell Aug 23rd, 2007 at 8:31 am

    FYI, Canada Post does not use the letters D, F, I, O, Q, and U in postal codes as they are too similar to other letters or numbers. This regex restricts even more:

    ^[A-CEG-NPR-TVXY][[:digit:]][A-CEG-NPR-TVW-Z]( |-)?[[:digit:]][A-CEG-NPR-TVW-Z][[:digit:]]$

    The above regex is more CF specific, but easy to adapt. I’m not sure if Flex allow posix classes.

  2. 2 peterd Aug 23rd, 2007 at 9:11 am

    Peter,

    Thanks for the tip/clarification! Flex (or more accurately Flash Player 9) does allow POSIX classes, as it turns out! I updated the entry above to show the POSIX style and admit to my own ignorance of the Canadian Postal system.

    Peter

  3. 3 peterd Aug 28th, 2007 at 9:15 pm

    For more information on the fascinating Canadian Postal code format, check out:
    http://www.infinitegravity.ca/postalcodeformat.htm
    http://en.wikipedia.org/wiki/Canadian_postal_code
    http://www.canadapost.ca/cpc2/addrm/hh/doc/faq-e.asp

    According to Ben Forta’s “Regular Expressions in 10 Minutes” book (First edition, page 121), the following regular expression should work for Canadian postal codes:

    [ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d

    Note that the D, F, I, O, Q, U, and Z characters are omited from the first allowed character range, but allowable in alphabetic later ranges.

    Peter

  4. 4 peterd Aug 29th, 2007 at 8:34 am

    For more information on POSIX regular expressions, check out the following URL:

    http://www.dc.turkuamk.fi/docs/gnu/rx/rx_3.html

    The link also mentions how you can use inverted character classes such as the following:

    [^[:space:]] - all non-whitespace characters
    
  5. 5 Ryan Swanson Oct 18th, 2008 at 9:43 pm

    Hi Peter,

    I am a frequent visitor to your blog and recently came across this article on Validating data using Regular Expressions. For a while now, I have been working on a sophisticated regular expression application and was just able to publish it this past week. Considering your interest and expertise with Flex and regular expressions, I thought you might be interested in it.

    The app is called the Flex 3 Regular Expression Explorer and can be found at my blog below.

    http://blog.ryanswanson.com/2008/10/introducing-flex-3-regular-expression.html

    The application is similar to the Flex Component and Style Explorers created by Adobe, but I have also added a collaborative community section where people can post their own regular expression examples as well as a full-feature help panel to get novices started with the technology.

    Hope you like it!

    Cheers,
    Ryan

    p.s. Considering your obvious abilities with Flex and regular expressions, I would be very grateful if you were a contributor to the Regular Expression Explorer community! The more we work together, the more we all profit. :)

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




Badge Farm

  • Firefox 2
  • Powered by Redoable 1.2
  • Feeds burnt by Feedburner
  • Feed