Validating User InputIn order to make your application as robust as possible, the best solution to invalid or incorrect user input is to prevent the entry of "bad" data as often as possible. Validating user input before it is evaluated provides a better solution than complex exception-handling code that may add a great deal of resource overhead to your program. Here are the four basic techniques used to validate user input:
Control-Based ValidationYou can restrict the allowable values within a control by using the properties that we discussed in Chapter 2, "Controls on Forms." In addition to simply restricting input to a selection from a list of values, configuration of control properties may be used in order to further limit possible input values. Of note are the CharacterCasing and MaxLength properties used in text-input controls such as the TextBox control. CharacterCasingThe CharacterCasing property of a TextBox control may be used to force all input alphabetic characters to a particular case. The options for the CharacterCasing property are Normal (the default, which does not change the case of input characters), Upper (which forces all input to uppercase), and Lower (which forces all input to lowercase). MaxLengthThe MaxLength property of a TextBox or ComboBox control is used to restrict the maximum number of characters the user can input into the control. A value of zero (the default) specifies no specific limit to the number of characters that may be input by the user. This property does not restrict the length of values that may be input programmatically. Control-Access RestrictionManipulating access properties such as the Enabled and ReadOnly properties can be used to restrict data entry access within a control. When a control's Enabled value is set to False, it cannot receive focus. If the ReadOnly property of a TextBox control is set to True, it may still receive focus, allowing users to scroll through its contents while preventing changes. Keystroke-Level ValidationWhen a user presses a key, three events are fired in order:
The KeyPress event may be used in order to intercept input keyboard characters and perform validation tasks through the use of the KeyPressEventArgs class before the KeyUp event is handled. Table 3.4 details some important properties of the KeyPressEventArgs class. Table 3.4. Important Properties of the KeyPressEventArgs Class
The KeyPress event only fires for keys that generate character values, excluding function, control, and cursor-movement keys. To respond to the excluded keys, you must use the KeyDown and KeyUp events instead. These use the properties of the KeyEventArgs class, detailed in Table 3.5. Table 3.5. Important Properties of the KeyEventArgs Class
Field-Level ValidationValidation may also be performed to include the entire value entered within a control by configuring validation code to run before focus is lost or the form is closed. When a user enters or leaves a field, the following events occur in order:
Of these events, the Validating event is most important for validating user input. That's because code within this event can halt the chain of events and prevent the user from moving on until any error is corrected. The Validating EventThe Validating event is ideal for input value validation, as you may write code to check the value presented and display an error message to the user, or prevent the loss of focus from the current control until the value has been corrected. The Focus method of the control may be used in order to redirect focus back to the same control programmatically, and the Cancel property of the CancelEventArgs object may be set to True, preventing the transfer of focus away from the current control.
The Validated event occurs after validation has occurred and may be used to perform actions based on the validated values, such as enabling or disabling other controls, as discussed previously in this section. The CausesValidation PropertyWhen using the Validating event to retain the focus in a control until a valid input value is received, you may prevent the user from being able to obtain help on what constitutes a valid input value by clicking another control such as the Help button in the toolbar. This is a result of the default setting (True) of the CausesValidation property of the Button control. If you set the CausesValidation property of the Help Button control to False, the control may act without first triggering the Validating event in the control with current focus. The ErrorProvider ComponentThe ErrorProvider component provided within the Visual Studio .NET toolbox allows for the display of error-validation messages using a small icon that includes a message that appears as a ToolTip when the user hovers his or her cursor over the displayed icon. Table 3.6 details the more important members of the ErrorProvider class. Table 3.6. Important Members of the ErrorProvider Class
Use of this component has many advantages over opening separate MessageBox components for each possible error, which may confuse users and complicate the desktop. The ErrorProvider component provides a simple user-friendly display that rapidly draws a user's attention to the control failing input validation. Figure 3.2 shows a form including an ErrorProvider component. Figure 3.2. A form displaying an example of the ErrorProvider component.
You may be tempted to omit validation from your applications. After all, if the user does exactly what you expect, your validation code will never be invoked. But generally speaking, this is a false economy. Users will find many ways to enter data that you never dreamed of. Validation code provides you with a way to correct problems immediately, and it can cut down on costly customer support. |