O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Validating User Input with Common Patterns

Problem

You want to make sure that a user correctly entered information, such as an email address, social security number, telephone number, or Zip/Postal Code.

Solution

Use one of the common patterns included in this recipe.

Discussion

Regular expressions are extremely useful for validating a wide range user input. For example, you might have a form that allows a user to enter an email address to sign up for your latest online game and you need to ensure the email address is valid. Or, you might possibly want to make sure that a birth date was entered correctly. Or, you might want to verify that a credit card number was input properly. The following list of regular expressions will help:

  • Match a date in the format ##/##/####, where both the day and month value can be 1 or 2 digits, and the year can be either 2 digits or 4 digits when starting with 19 or 20:

  • ^\\d{1,2}\\/\\d{1,2}\\/(\\d{2}|(19|20)\\d{2})$
  • Match a social security number in the format ###-##-####, where the dashes are optional and the three groups can have optional spacing between them:

  • ^\\d{3}\\s*-?\\s*\\d{2}\\s*-?\\s*\\d{4}$
  • Match a five-digit U.S. Zip Code with an optional dash and four-digit extension:

  • ^\\d{5}(-\\d{4})?$
  • Match a Canadian Postal Code in the format L#L #L# (where L is a letter). There is a restriction placed on the first letter in the Postal Code to ensure that a valid province, territory, or region is specified:

  • ^[ABCEGHJKLMNPRSTVXY]\\d[A-Z] \\d[A-Z]\\d$
  • Match a U.S. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required