Validating User Input

Validating User Input

In 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:

  • Restricting the available values by using the proper type of control, configured with a specific list of allowed values. Controls such as RadioButtons, ListBoxes, ComboBoxes, and CheckBoxes are often used for this type of validation. Configuring the properties of the controls allows for additional restriction of user input, such as controlling the case or length of text box 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 for the entry of address information might remain disabled until a valid customer ID 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 symbols 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 close the form.

Control-Based Validation

You 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.

CharacterCasing

The 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).

MaxLength

The 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 Restriction

Manipulating 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 Validation

When a user presses a key, three events are fired in order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

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

Property

Description

Handled

Indicates whether the event has been handled.

KeyChar

The character value corresponding to the pressed key.

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

Property

Description

Alt

True if the Alt key is pressed; otherwise False.

Control

True if the Ctrl key is pressed; otherwise 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) were pressed.

Shift

True if the Shift key is pressed; otherwise, False.

graphics/note_icon.gif

By default, only the control with the focus will respond to the KeyDown, KeyPress , and KeyUp events. If you set the KeyPreview property of a form to True, then the form will handle the same three events before the control with the focus handles them, thus allowing two tiers of keystroke-level validation.


Field-Level Validation

Validation 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:

  1. Enter (the focus is about to enter the control)

  2. GotFocus (the focus has entered the control)

  3. Leave (the focus is about to leave the control)

  4. Validating (the data in the control is ready to validate)

  5. Validated (the data has been validated)

  6. LostFocus (the focus has left the control)

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 Event

The 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.

graphics/tip_icon.gif

Closing a form fires the Validating event. If you set the Cancel property to True during a Validating event when the form is being closed, this will prevent the form from closing. You can use the Closing event of the form to determine whether the form is closing and disable validation in this case, if you like.


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 Property

When 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 Component

The 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

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

The location at which to place an error icon with respect to the control.

SetIconPadding

Method

The amount of extra space to leave between the specified control and its error icon.

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.

graphics/03fig02.jpg

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.



Developing and Implementing WindowsR-based Applications with Visual BasicR. NET and Visual StudioR. NET Exam CramT 2 (Exam 70-306)
Developing and Implementing WindowsR-based Applications with Visual BasicR. NET and Visual StudioR. NET Exam CramT 2 (Exam 70-306)
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 188

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net