Java Reference
In-Depth Information
Note in this case that it is important to set the case-insensitive fl ag by adding an i on the end of the
expression defi nition; otherwise, the regular expression could fail to match the ext parts. Please also
note that the regular expression itself must be on one line in your code — it's shown in four lines here due
to the page-width restrictions of this topic.
Validating a Postal Code
We just about managed to check worldwide telephone numbers, but doing the same for postal codes
would be something of a major challenge. Instead, you'll create a function that only checks for U.S. zip
codes and UK postcodes. If you needed to check for other countries, the code would need modifying. You
may fi nd that checking more than one or two postal codes in one regular expression begins to get unman-
ageable, and it may well be easier to have an individual regular expression for each country's postal code
you need to check. For this purpose though, let's combine the regular expression for the UK and the U.S.:
^(\d{5}(-\d{4})?|[a-z][a-z]?\d\d? ?\d[a-z][a-z])$
This is actually in two parts: The fi rst part checks for zip codes, and the second part checks UK post-
codes. Start by looking at the zip code part.
Zip codes can be represented in one of two formats: as fi ve digits (12345), or fi ve digits followed by a
dash and four digits (12345-1234). The zip code regular expression to match these is as follows:
\d{5}(-\d{4})?
This matches fi ve digits, followed by an optional non-capturing group that matches a dash, followed by
four digits.
For a regular expression that covers UK postcodes, let's consider their various formats. UK postcode
formats are one or two letters followed by either one or two digits, followed by an optional space, fol-
lowed by a digit, and then two letters. Additionally, some central London postcodes look like this: SE2V
3ER, with a letter at the end of the fi rst part. Currently, it is only some of those postcodes starting with
SE, WC, and W, but that may change. Valid examples of UK postcode include: CH3 9DR, PR29 1XX, M27
1AE, WC1V 2ER, and C27 3AH.
Based on this, the required pattern is as follows:
([a-z][a-z]?\d\d?|[a-z]{2}\d[a-z]) ?\d[a-z][a-z]
These two patterns are combined using the | character to “match one or the other” and grouped using
parentheses. You then add the ^ character at the start and the $ character at the end of the pattern to be
sure that the only information in the string is the postal code. Although postal codes should be upper-
case, it is still valid for them to be lowercase, so you also set the case-insensitive option as follows when
you use the regular expression:
^(\d{5}(-\d{4})?|([a-z][a-z]?\d\d?|[a-z{2}\d[a-z]) ?\d[a-z][a-z])$
The following function needed for your validation module is much the same as it was with the previous
example:
function isValidPostalCode( postalCode )
{
Search WWH ::




Custom Search