.NET ZIP Code Validation Using Regular Expressions

by Kevin Couch

Share This Article

Web developers often have requirements to build forms on web pages for users to fill out. Many websites request a physical postal address for such purposes as contact information or billing data for ecommerce. Besides requiring that certain fields just have data, a form can also verify that the data is in a valid format. This can be tricky for ZIP codes because of the different formats that are valid. Having two textboxes is one option, a box for each set of numbers, but having one textbox can still be done easily using a regular expression for validation.

A web user from the United States will frequently know a ZIP code with 5 digits (63017), but a developer may also want to allow the format known as ZIP+4 (63017-0764) which has four extra digits, and those four are separated from the first 5 digits with a hyphen.

Format validation of data can be done on the client using Javascript or server-side such as with .NET code. This .NET control validates a textbox for a five or nine digit ZIP code.

<asp:RegularExpressionValidator
 ValidationExpression="^[0-9]{5}(-[0-9]{4})?$"
ControlToValidate="txtZIPcode"
ID="RegExpVal_txtZIPcode" runat="server"
ErrorMessage="Invalid Format (use: ##### or #####-####)"
 Display=”Dynamic" />

The regular expression used above can also be rewritten using \d to match the numeric digits. Having an expression in parentheses followed by a question mark makes the inner part optional. In these examples the hyphen and 4 extra digits will not be required.

^\d{5}(-\d{4})?$

For postal codes in Canada, the format is “A1A 2B2”, and it is made up of two parts. In this example the case-insensitive modifier (i) is used.

^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i

Even though the letters D, F, I, O, Q, or U are not used in a postal code, a less verbose version could be made like the following.

^[A-Z]\d[A-Z]( )?\d[A-Z]\d$/i

Other countries around the world have many different varying formats. While it is possible to create validation expressions to match them, if you have a form collecting any international address, it may be best not to validate it at all in order to avoid having a small coding error that prevents a web user from submitting the data at all.