Device screens surrounded with gear icons.

.NET Zip Code Validation

Web developers often have requirements to web pages with custom forms, where users fill out their information. Many websites request a physical postal address for contact or billing information. Forms can require specific fields have the intended data entered by users. Additionally, a form can also verify data entered is in a valid format. ZIP codes pose a challenge because of the various formats used around the globe. In the past, you might think having two textboxes would work for this situation, where each box includes a set of numbers. However, one textbox is easy to maintain using regular expressions for validation.

Web users in the United States typically know a ZIP code with five digits (63017). Still, a developer may also want to allow the format known as ZIP+4 (63017-0764), which has four different numbers separated by a hyphen. Format validation of data can be done on the client using JavaScript, or server-side, using .NET code like below.

Example Validation for 5- or 9-Digit ZIP Codes:

<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 from above can also be rewritten using \d to match the numeric digits, illustrated in the example below. Using an expression in parentheses followed by a question mark makes the inner part optional.

Example Not Requiring Extra 4-Digits or Hyphens:

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

Canadian postal codes use the format “A1A 2B2.” This format is made up of two parts. In this example, the case-insensitive modifier (i) is used.

Example of Case-Insensitive Modifier:

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

Although the letters D, F, I, O, Q, and U are not used in ZIP codes, a less verbose version of the example above would also work for validation.

Example of Shortened Case-Insensitive Modifier:

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

Countries around the world use ZIP code formats not addressed in the examples above. It is possible to create validation expressions to match every possible international design; it’s best to change approaches. When international addresses are submitted through your web form, reducing the validation included is the best option. Doing so minimizes the chances for minor coding errors, preventing users from submitting web form data.

To learn more .NET tips and tricks from development experts, contact Unidev.