Validating User Input
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 hand provides a better solution than very complex error-handling code that might add a great deal of resource overhead to your program. Four basic techniques are used to validate user input:
Restricting the available values by using the proper type of control, configured with a specific list of allowed values. Controls such as RadioButton, ListBox, ComboBox, and CheckBox are often used for this type of validation. Configuring properties of the controls allows additional restriction of user input, such as controlling the case or length of TextBox input.
Restricting data entry through controls by enabling or disabling them based on the state of other controls. As an example of this technique, a set of controls allowing the entry of address information might remain disabled until a valid CustomerID has been selected in another control.
Capturing and evaluating user keystrokes and allowing only acceptable values to be recognized. This might be used to prevent the entry of symbol or alphabetic characters within a control that should hold only numeric characters.
Evaluating a control's data as a whole and warning the user of incorrect or unacceptable values. This is often used to warn a user when attempting to change focus from the control or save the form.
Control-Based Validation
Restriction of allowable values within a control was discussed at greater length in Chapter 2, "Controls on Forms." In addition to simply restricting input to a selection from a list of values, control properties can be configured to further limit possible input values. Of note are the CharacterCasing and MaxLength properties used in text input controls such as the TextBox.
CharacterCasing
The CharacterCasing property of a TextBox control can be used to change 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 (changes all the characters to uppercase), and Lower (changes all the characters to lowercase).
MaxLength
The MaxLength property of a TextBox or ComboBox is used to restrict the maximum number of characters the user can input into the control. A value of 0 (the default) specifies no specific limit for the number of characters that can be entered by the user. This property does not restrict the length of values that can be set programmatically.
Control-Access Restriction
Manipulating access properties such as the Enabled or ReadOnly properties can 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 can still receive focus, allowing users to scroll through its contents while preventing changes.
Keystroke-Level Validation
When a user presses a key, three events are fired in order:
KeyDown
KeyPress
KeyUp
The KeyPress event can be used 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
Property |
Description |
Handled |
Whether the event has been handled. |
KeyChar |
The character value corresponding to the pressed key. |
The KeyPress event fires only 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
Property |
Description |
Alt |
Is true if the Alt key is pressed; otherwise, is false. |
Control |
Is true if the Ctrl key is pressed; otherwise, is false. |
Handled |
Indicates whether the event has been handled. |
KeyCode |
The keyboard code for the event. Its value is one of the values specified in the Keys enumeration. |
KeyData |
The key code for the pressed key, along with modifier flags that indicate the combination of Ctrl, Shift, and Alt keys that were pressed at the same time. |
KeyValue |
An integer representation of the KeyData property. |
Modifiers |
Modifier flags that indicate which combination of modifier keys (Ctrl, Shift, and Alt) was pressed. |
Shift |
Is true if the Shift key was pressed; otherwise, is false. |
NOTE
By default, only the control, which currently has the focus, responds to the KeyDown, KeyPress, and KeyUp events. However, if you set the KeyPreview property of a form to true, the form can also handle the same three events before the control with the current focus handles them, allowing two tiers of keystroke-level validationat the form level and at the control level.
Field-Level Validation
Validation also can 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:
EnterOccurs when a control is entered
GotFocusOccurs when a control receives focus
LeaveOccurs when focus leaves a control
ValidatingOccurs when a control is validating
ValidatedOccurs when a control is finished validating
LostFocusOccurs when a control loses focus
The Validating event is the ideal place to store the validating logic for a field; we discuss the Validating event in the next section.
The Validating Event
The Validating event is ideal for input value validation. You can write code to check the values 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 can be used to redirect focus to the same control programmatically. Alternatively, the Cancel property of the CancelEventArgs object can be set to true, to prevent the transfer of focus from the current control.
TIP
Closing a form fires a Validating event. Therefore, if you want to use the Cancel property of the CancelEventArgs to prevent loss of focus, this will also prevent the user from closing the form. To avoid this, you need to code the event handling to reset the Cancel value only when the mouse is inside the form's client area. This allows the mouse to close the form using the Close button in the title bar.
The Validated event occurs after validation has occurred. It can 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 Property
When using the Validating event to retain the focus in a control until you receive a valid input value, you can prevent the user from being able to obtain help on what constituted 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 can act without triggering the Validating event in the control with current focus.
The ErrorProvider Component
The ErrorProvider component provided within the Visual Studio .NET toolbox allows the display of error validation messages. A small icon includes a message that appears as a ToolTip when the user hovers the cursor over the displayed icon. Table 3.6 details the most important members of the ErrorProvider class.
Table 3.6 Important Members of the ErrorProvider Class
Member |
Type |
Description |
BlinkRate |
Property |
Specifies the rate at which the error icon flashes. |
BlinkStyle |
Property |
Specifies a value indicating when the error icon flashes. |
ContainerControl |
Property |
Specifies the parent control of the ErrorProvider control. |
GetError |
Method |
Returns the error description string for the specified control. |
Icon |
Property |
Specifies an icon to display next to the parent control. The icon is displayed only when an error-description string (SetError) has been set for the parent control. |
SetError |
Method |
Sets the error-description string for the specified control. |
SetIconAlignment |
Method |
Specifies the location at which to place an error icon in relation to the control. |
SetIconPadding |
Method |
Specifies the amount of extra space to leave between the specified control and its error icon. |
This component offers many advantages over opening separate message boxes for each possible error, which can 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 that includes an ErrorProvider component.
Figure 3.2 A form displaying an example of the ErrorProvider component.
The following code shows how the ErrorProvider component can be used together with the Validating event to display errors during validation:
private void txtGallons_Validating(object sender, System.ComponentModel.CancelEventArgs e) { try { decimal decGallons = Convert.ToDecimal(txtGallons.Text); if (decGallons > 0) errorProvider1.SetError(txtGallons, ""); else errorProvider1.SetError( txtGallons, "Please enter value > 0"); } catch(Exception ex) { errorProvider1.SetError(txtGallons, ex.Message); } }
In this section, we discussed various techniques that can be used for user input validation. You also learned how the ErrorProvider component can be used to point to errors when the user enters input data on a Windows Form.