Welcome!

.NET Authors: Liz McMillan, Yakov Werde, Matthew Pollicove , Kevin Benedict

Related Topics: .NET

.NET: Article

Error Prevention in VS.NET

Use data validation to eliminate errors before they occur

With the release of Visual Studio .NET and the structured error-handling capabilities of the .NET Framework came significant improvements in the way that VS programmers are able to capture and deal with programmatic errors. Yet these more robust abilities do not lessen the importance of one of the most time-tested means of error handling: prevention.

In this article I will highlight various methods of data validation that can be used to eliminate potentially problematic errors before they have a chance to occur. Data validation checks any inputted data for potential problems prior to the data being passed on to the program logic associated with application functionality. This article will give an overview of the two major types of data validation, field-level and form-level.

Field-Level Validation
Field-level validation deals with data that is being entered or that was entered into an individual data entry field such as a single text box. Thus, the purpose of field-level validation is to ensure that the supplied data is valid in both value and format.

One of the simplest ways to provide this type of functionality is to simply restrict the type of input that the program user is allowed to supply. For example, the MaxLength or MultiLine property of a text box could easily be set to restrict the length of the input value. Likewise, if only a small range of possibilities is acceptable, a drop-down list may be preferred over a text box, because it would restrict user choices to a predetermined list.

A more sophisticated variation of this technique is to add code to the input fields' KeyPress, KeyUp, or KeyDown events as a means of examining keyboard input as it is entered. The KeyPress event is especially useful because it allows us to examine all ASCII-based input into a given field.

For example, if we need to create a text box that can accept only numeric input, we may want to warn users if they instead type in a nonnumeric ASCII character. We could accomplish this using the code found in Listing 1. As you can see, when the KeyPress event is raised, the IsDigit method of the Char namespace is used to check whether the input character is a valid numeric character. The Char namespace also contains a variety of other methods that can be used to validate letters, punctuation, and white space. These methods are summarized in Table 1.

While these keyboard-based techniques are not without merit, they do have limitations in the complexity of the inputs that they are able to validate. For example, writing validation code for a date using such techniques would not be a straightforward task, since a digit is proper in certain places while a slash (/) is appropriate in others, e.g., 3/1/04. Performing this type of field-level validation is much better accomplished by first allowing the user to completely enter the input value into the field, and then validating the entire entry.

In past versions of VB such types of validation were usually performed using the LostFocus or Leave events. However, VS.NET has a special event for this purpose, the Validating event. This event occurs just after the Leave event but before the LostFocus event, thus the user can be prevented from moving on to the next field if the entered data is not satisfactory.

In order to use the Validating event, the CausesValidation property of the control must first be set to true. If the property is set to false, the Validating event will be suppressed. Thus, for example, if we have a text box that requires a valid date as an input value, we could use the Validating event as shown in Listing 2 to check the suitability of the entered information.

In this case we use the Visual Basic function IsDate, but when writing such validation routines it's a good idea to keep regular expressions in mind (see "Demystifying Regular Expressions," [.NETDJ, Vol. 2, issue 3]), since a properly coded regular expression can provide sophisticated formatting checks. Additionally, the substitution abilities of the regular expression class can allow your program code to convert the field value to a format that may be more appropriate for later processing, such as a standardized telephone number or date format. Within the validation procedure, if the field data is not valid we can also cause the e.Cancel property to be set to false, which will keep the focus on the text box of interest. This forces users to deal with the incorrect entry before they are able to move on.

When dealing with data validation it is also wise to add an ErrorProvider control to the form since this will provide a way of notifying the user of the problem in a manner that is much less obtrusive than the message box approach we used in the first example. With the SetError method the error provider displays a warning icon next to the control with the problematic input, and a tool tip containing an error message will be displayed when the user positions the mouse over the icon.

When using error-provider controls it is also important to remove their warnings after the error has been removed, thus when a valid date is entered, the error message is set to a null string. The presence of the null string will cause the error-provider icon to become hidden and thus alert the user that the problem has been properly corrected.

Form-Level Validation
As we saw above, field-level validation is a useful means of validating the data entered into any given field, but it has some limitations. The major limitation is that field-level validation requires that the user actually enter data into the field in order for any type of validation to be performed. Thus field-level validation does not provide an adequate means of determining whether or not all required fields were properly filled in. For this type of functionality we must turn to form-level validation.

Form-level validation allows us to validate the content of one or more controls on the form. Such validation is generally tied to the click event of the button control that will initiate further processing of the entered data. It is important, however, to make sure that the validation code is placed prior to any information-processing code in the click event to ensure that potential errors are eliminated before they can become problematic.

For example, let's consider the code shown in Listing 3, which will check all the fields on a given form (in this case two text boxes) and notify the user if any fields have been left blank. As in the previous example, if a blank field is detected, we alert the user via an error-provider control. More important, however, is that prior to validating any of the fields on the form, a MissingField variable is defined and set to a default value of false. If any missing fields are discovered, this variable is set to true.

In the final part of our validation code the MissingField variable is checked to ensure that it has retained a false value before any of the program logic is allowed to execute. In this way a checkpoint is established that ensures that the data validation code has successfully been passed before the program can proceed. While such a simplistic checkpoint may not be appropriate for all applications, the checkpoint architecture should be employed when performing form-level validation.

Conclusion
As you have seen in this article, validation at both the form and field levels can be readily employed. Taking the extra time to write the validation code is worthwhile, as proper validation can be a highly beneficial means of error prevention. It will ensure that the program logic will see only input data in forms that it was designed to process. Thus, when planning ways to bulletproof your next application, remember the old adage "an ounce of prevention is worth a pound of cure."

More Stories By Christopher Frenz

Christopher Frenz is the author of "Visual Basic and Visual Basic .NET for Scientists and Engineers" (Apress) and "Pro Perl Parsing" (Apress). He is a faculty member in the Department of Computer Engineering at the New York City College of Technology (CUNY), where he performs computational biology and machine learning research.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.