Chapter 5. Validation

As you have seen in the preceding chapters, many web applications involve user input. The sad fact is, however, that users make mistakes: they skip required fields, they put in six-digit phone numbers, and they return all manner of incorrectly formatted data to your application. Your database routines can choke on corrupted data, and orders can be lost. An incorrectly entered credit card number or omitted address may result in a missed sales opportunity. Fortunately, you can write code that checks the user’s input before it gets anywhere near your database code, or anything else dangerous. The process of verifying the user’s input is called validation.

Traditionally, it takes a great deal of time and effort to write reliable validation code. You need to check each field and create routines for ensuring data integrity. If bad data is found, you need to display an error message so the user knows there is a problem and how to correct it.

In a given application, you may choose to verify that the data is formatted correctly, or the values fall within a given range, or that certain fields have a value at all. For example, if you’re processing an order, you may need to ensure that the user has input an address and phone number, that the phone number has the right number of digits (and no letters), and that the Social Security number entered is in the appropriate form of nine digits separated by hyphens.

Some applications require more complex validation, in which you ...

Get Learning ASP.NET 2.0 with AJAX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.