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]).
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
10 Responses to Validating data using Regular Expressions
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


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.
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
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:
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
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:
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. :)
Thanks Peter,
This restrict property helps me a lot in my flex application, Appreciate your good work
Anuj
couldn’t you just use the built in ZipCodeValidator with domain=”Canada Only” ?
Anyway, it’s nice to know about the POSIX support
Cheers,
Matt
@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
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
this not what i want