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.

<?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]).

10 thoughts on “Validating data using Regular Expressions

  1. 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. 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. 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. 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. :)

  5. Thanks Peter,
    This restrict property helps me a lot in my flex application, Appreciate your good work
    Anuj

    1. @Matt Reynolds,

      Excellent question! The “Canada Only” was actually bug fix/enhancement in a later Flex 3 SDK. It wasn’t available when I did this post, but I really should update this post with that new information since it seems like overkill to use a simple RegEx validator when the ZipCodeValidator would do (unless you want to do more complex Canadian postal code validations as mentioned previously in some other reader comments).

      Thanks,
      Peter

  6. Hi
    I have need Find Pattern who have check any type Mathematical expression is a regular Expression or not.
    When i have used Pattern = /^[-+*()%\/]?\d*[-+*()%]+\d*[-+*()%\/]+\d*[-+*()%\/]+$/ for String = “+41+(-12)*(-12)”

    this is true, But when String = “+41+(-12)*(-12)+11(-2)”, this show wrong.
    plz send generalize formate for pattern.

    hanks
    Bambam

Comments are closed.