Lesson 5: Validating User Input

Lesson 5: Validating User Input

In most applications, the user enters information for the application through the user interface. Data validation ensures that all data entered by a user falls within acceptable parameters before proceeding with program execution. For example, you might have a field where a user enters a zip code as part of an address. Using validation, you could verify that the field contained five and only five characters, all of which were numeric, before proceeding. Validating user input reduces the chance of an input error and makes your application more robust.

In this lesson, you will learn how to use events to validate user input and direct the focus on your forms. You will learn to use field-level validation, which validates entries as they are made, and form-level validation, which validates all the entries on a form at once. You will learn to use control properties to help restrict input, and you will use the ErrorProvider component to provide error messages to your users.

After this lesson, you will be able to

  • Explain the difference between form-level and field-level validation

  • Direct the focus using control methods and events

  • Implement form-level validation for your form

  • Implement field-level validation for your form

Estimated lesson time: 30 minutes

You can choose between two different types of validation for user input: form-level validation and field-level validation. Form-level validation verifies data after the user has filled in all the fields. For example, a user might be directed to fill in a name, address, and phone number, and then click OK. With form-level validation, all the fields on the form would be validated when the user clicked OK.

Field-level validation, on the other hand, verifies that the data in each field is appropriate. For example, if a user fills in a field that holds a phone number, field-level validation can verify that the number contains a valid area code before moving to the next field. As each digit is entered, control events can verify that only numbers are entered.

Field-Level Validation

You might want to validate data as it is entered into each field. Field-level validation gives you control over user input as it occurs. In this section, you will learn how to use control events to validate user input and how to use TextBox control properties to help restrict input to appropriate parameters.

Using TextBox Properties

The TextBox control is the most common control for user input. Several TextBox control properties let you restrict user input values to only those that are acceptable. Some of these properties include

  • MaxLength

  • PasswordChar

  • ReadOnly

  • MultiLine

Setting the MaxLength Property

The MaxLength property limits the number of characters that can be entered into a text box. If the user attempts to exceed the number returned by MaxLength, the text box will accept no further input and the system will beep to alert the user. This property is useful for text boxes that always contain data of the same length, such as a zip code field.

Using the PasswordChar Property

The PasswordChar property allows you to hide user input at run time. For example, if you set the PasswordChar property to an asterisk (*), the text box will display an asterisk for each character, regardless of user input. This behavior is commonly seen in password logon boxes.

Although an asterisk is the character most commonly used for passwords, you can choose any valid character semicolons or ampersands, for example. The Text property value is always set to the value the user enters, regardless of the password character.

Setting the ReadOnly Property

The ReadOnly property determines whether a user can edit the value displayed in a text box. If ReadOnly is set to true, the text cannot be changed by user input. If ReadOnly is set to false, the user can edit the value normally.

Using the MultiLine Property

The MultiLine property determines whether a text box can accept multiple lines. When set to true, the user can enter multiple lines in the text box, each separated by a carriage return. The individual lines are stored as an array of strings in the TextBox.Lines collection and can be accessed by their index.

Using Events in Field-Level Validation

Field-level keyboard events allow you to immediately validate user input. Controls that can receive keyboard input raise the following three keyboard events:

  • KeyDown

  • KeyPress

  • KeyUp

KeyDown and KeyUp

The KeyDown and KeyUp events are raised when a key is pressed and a key is released, respectively. The control that has the focus raises the event. When these events are raised, they package information about which key or combination of keys were pressed or released in an instance of KeyEventArgs, a class that describes the key combination. A method that handles the KeyDown or KeyUp event must include a KeyEventArgs parameter in its signature. Properties of KeyEventArgs are summarized in Table 2.4.

Table 2-4. KeyEventArgs Properties

Property

Description

Alt

Gets a value describing whether the Alt key was pressed

Control

Gets a value describing whether the Ctrl key was pressed

Handled

Gets or sets a value indicating whether the event was handled

KeyCode

Returns an enum value representing which key was pressed

KeyData

Returns data representing the key that was pressed, together with whether the Alt, Ctrl, or Shift key was pressed

KeyValue

Returns an integer representation of the KeyData property

Modifiers

Gets the modifier flags for the event, indicating what combination of Alt, Ctrl, or Shift keys was pressed

Shift

Gets a value describing whether the Shift key was pressed

The KeyUp and KeyDown events are most commonly used for determining if the Alt, Ctrl, or Shift key has been pressed. This information is exposed through properties in the KeyEventArgs reference that is passed to the handler. The KeyEvent Args properties Alt, Control, and Shift are properties that return a Boolean value, which indicates whether those keys are down. A value of true is returned if the corresponding key is down, and false is returned if the key is up. The following code demonstrates a KeyUp event handler that checks whether the Alt key is pressed:

Visual Basic .NET

Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp If e.Alt = True Then MessageBox.Show("The ALT key is still down") End If End Sub

Visual C#

private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.Alt == true) MessageBox.Show("The ALT key is still down"); }

You also can use the KeyEventArgs.KeyCode property to examine the actual key that triggered the event. This property returns a Key value that represents the key that was pressed (in the case of a KeyDown event) or released (in the case of a KeyUp event). The following code shows a simple event handler that displays a message box containing a string representation of the key that was pressed:

Visual Basic .NET

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown MessageBox.Show(e.KeyCode.ToString()) End Sub

Visual C#

private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { MessageBox.Show(e.KeyCode.ToString()); }

KeyPress

When a user presses a key that has a corresponding ASCII value, the KeyPress event is raised. Keys with a corresponding ASCII value include any alphabetic or numeric characters (alphanumeric a z, A Z, and 0 9), as well as some special keyboard characters, such as the Enter and Backspace keys. If a key or a key combination does not produce an ASCII value, it will not raise the KeyPress event. Examples of keys that do not raise this event include Ctrl, Alt, and the function keys.

This event is most useful for intercepting keystrokes and evaluating them. When this event is raised, an instance of KeyPressEventArgs passes to the event handler as a parameter. The KeyPressEventArgs instance contains information about the keystroke that can be used for validating user input. The KeyPressEventArgs.KeyChar property contains the ASCII character represented by the keystroke that raised the event. If you want to make sure that the key pressed was a numeric key, for example, you can evaluate the KeyChar property in your KeyPress event handler. The KeyPressEventArgs.Handled property can be used to set whether this event has been handled.

Validating Characters

The Char data type contains several Shared (static) methods that are useful for validating characters trapped by the KeyPress event. These methods include

  • Char.IsDigit

  • Char.IsLetter

  • Char.IsLetterOrDigit

  • Char.IsPunctuation

  • Char.IsLower

  • Char.IsUpper

Each of these methods, with their descriptive names, evaluates a character and returns a Boolean value. The Char.IsDigit function returns true if a character is a numeric digit and false if it is not. The Char.IsLower function returns true if a character is a lowercase letter, false otherwise. The other methods behave similarly. The following code uses the Char.IsNumber method to test whether the key pressed was a numeric key:

Visual Basic .NET

Private Sub TextBox1_KeyPress (ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress If Char.IsDigit(e.KeyChar) = True Then MessageBox.Show("You pressed a number key") End If End Sub

Visual C#

private void textBox1_KeyPress (object sender, System.Windows.Forms.KeyPressEventArgs e) { if (Char.IsDigit(e.KeyChar) == true) MessageBox.Show("You pressed a number key"); }

Handling the Focus

Focus is the ability of an object to receive user input through the mouse or the keyboard. Although you can have several controls on your form, only one can have the focus at any given time. The control that has the focus is always on the active form of the application.

Every control implements the Focus method. This method sets the focus to the control that called it. The Focus method returns a Boolean value that indicates whether the control was successful in setting the focus. Disabled or invisible controls cannot receive the focus. You can determine whether a control can receive the focus by checking the CanFocus property, which returns true if the control can receive the focus and false if it cannot.

Visual Basic .NET

' This example checks to see if TextBox1 can receive the focus and ' sets the focus to it if it can. If TextBox1.CanFocus = True Then TextBox1.Focus() End If

Visual C#

// This example checks to see if textBox1 can receive the focus and // sets the focus to it if it can. if (textBox1.CanFocus == true) textBox1.Focus();

Focus events occur in the following order:

  1. Enter

  2. GotFocus

  3. Leave

  4. Validating

  5. Validated

  6. LostFocus

The Enter and Leave events are raised when the focus arrives at a control and when the focus leaves a control, respectively. GotFocus and LostFocus are raised when a control first obtains the focus and when the focus leaves the control, respectively. Although you can use these events for field-level validation, the Validating and Validated events are more suited to that task.

The Validating and Validated Events

The easiest way to validate data is to use the Validating event. The Validating event occurs before a control loses the focus. This event is raised only when the CausesValidation property of the control that is about to receive the focus is set to true. Thus, if you want to use the Validating event to validate data entered in your control, the CausesValidation of the next control in the tab order should be set to true. To use Validating events, the CausesValidation property of the control to be validated also must be set to true. By default, the CausesValidation property of all controls is set to true when controls are created at design time. Typically, the only controls that have CausesValidation set to false are controls such as Help buttons.

The Validating event allows you to perform sophisticated validation on your controls. For example, you can implement an event handler that tests whether the value entered corresponds to a specific format. Another possible use is an event handler that disallows the focus to leave the control until a suitable value has been entered.

The Validating event includes an instance of the CancelEventArgs class. This class contains a single property, Cancel. If the input in your control does not fall within required parameters, you can use the Cancel property within your event handler to cancel the Validating event and return the focus to the control.

The Validated event fires after a control has been successfully validated. You can use this event to perform any actions based on the validated input.

The following code demonstrates a handler for the Validating event. This method requires an entry in TextBox1 before it will allow the focus to move to the next control.

Visual Basic .NET

Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As _ System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating ' Checks the value of TextBox1 If TextBox1.Text = "" Then ' Resets the focus if there is no entry in TextBox1 e.Cancel = True End If End Sub

Visual C#

private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e) { // Checks the value of textBox1 if (textBox1.Text == "") // Resets the focus if there is no entry in TextBox1 e.Cancel = true; }

To use the Validating event of a text box

  1. Add a text box to a form.

  2. Create an event handler to handle the Validating event for the text box. In the event handler, set the e.Cancel property to true to cancel validating and return the focus to the text box.

  3. Set the CausesValidation property to false for any controls for which you do not want the Validating event to fire.

Form-Level Validation

Form-level validation is the process of validating all fields on a form at once. A centralized procedure implements form-level validation and is usually called when the user is ready to proceed to another step. Implementing a form-level keyboard handler is a more advanced method of form-level validation.

The following code demonstrates how to create a form-level validation method. When a button named btnValidate is pressed, the sample tests whether all the text boxes on a form have received input and then resets the focus to the first text box it encounters with no input.

Visual Basic .NET

Private Sub btnValidate_Click(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles btnValidate.Click Dim aControl As System.Windows.Forms.Control ' Loops through each control on the form For Each aControl In Me.Controls ' Checks to see if the control being considered is a Textbox and ' if it contains an empty string If TypeOf aControl Is TextBox AndAlso aControl.Text = "" Then ' If a textbox is found to contain an empty string, it is ' given the focus and the method is exited. aControl.Focus() Exit Sub End If Next End Sub

Visual C#

private void btnValidate_Click(object sender, System.EventArgs e) { // Loops through each control on the form foreach (System.Windows.Forms.Control aControl in this.Controls) { // Checks to see if the control being considered is a Textbox // and if it contains an empty string if (aControl is System.Windows.Forms.TextBox & aControl.Text == "") { // If a textbox is found to contain an empty string, it is // given the focus and the method is exited. aControl.Focus(); return; } } }

Form-Level Keyboard Handler

A keyboard handler is a somewhat more sophisticated technique for form-level validation. A centralized keyboard handler allows you to manage data input for all fields on a form. For example, you can create a method that enables command buttons only after appropriate input has been entered into each field and that performs specific actions with each keystroke.

The KeyPress, KeyDown, and KeyUp events are used to implement a form-level keyboard handler. If a form has no visible or enabled controls, it will raise keyboard events. If the form has controls, however, these events will not be raised. For the form to raise these events, the KeyPreview property of the form must be set to true. When set to true, the form raises keystroke events before the control that has the focus. For example, assume that there is a KeyPress handler for the form, that there is a KeyPress handler for a text box on that form, and that the KeyPreview property of the form is set to true. When a key is pressed, the form raises the KeyPress event first and the form s KeyPress event handler executes first. When execution is complete, the text box s KeyPress event handler will execute.

If you are using form-level validation, you can prevent a control s KeyPress event handler from executing by setting the KeyPressEventArgs.Handled property to True, as shown in the following example:

Visual Basic .NET

Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress ' This handles the event and prevents it from being passed to ' the control's KeyPress event handler e.Handled = True End Sub

Visual C#

private void Form1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { // This handles the event and prevents it from being passed to // the control's KeyPress event handler e.Handled = true; }

Providing User Feedback

When invalid input is entered into a field, the user should be alerted and given an opportunity to correct the error. There are many ways to inform the user of an input error. If the error is obvious and self-explanatory, an audio cue can alert the user to the problem. In Visual Basic .NET, the Beep method produces an attention-getting sound.

Visual Basic .NET

' This line causes an audible beep Beep()

NOTE
Visual C# does not have an inherent beep function.

Other ways to draw a user s attention to an error include changing a control s BackColor or ForeColor. For example, a text box with invalid input could have its BackColor changed to red.

If a more detailed message is required, you can use the MessageBox.Show method. This method displays a small, modal dialog box with an informative message. Because the dialog box is displayed modally, it halts program execution and is impossible for the user to ignore. The following example shows how to call the MessageBox.Show method, along with an informative message:

Visual Basic .NET

MessageBox.Show("That value is not valid for this control")

Visual C#

MessageBox.Show("That value is not valid for this control");

The ErrorProvider Component

The ErrorProvider component provides an easy way to communicate validation errors to your users. The ErrorProvider allows you to set an error message for each control on your form whenever the input is invalid. An error message produces an error icon next to the control, and error message text is shown as a Tool Tip when the mouse hovers over the affected control. The ErrorProvider component is found in the Windows Forms tab of the Toolbox.

Displaying an Error

To cause an error condition to be displayed next to a control, you use the SetError method of the ErrorProvider component. The SetError method requires the name of the control to be set and the text to be provided. The method is invoked as shown:

Visual Basic .NET

' This example assumes the existence of a control named nameTextBox ' and an ErrorProvider named myErrorProvider myErrorProvider.SetError(nameTextBox, "Name cannot be left blank!")

Visual C#

// This example assumes the existence of a control named nameTextBox // and an ErrorProvider named myErrorProvider myErrorProvider.SetError(nameTextBox, "Name cannot be left blank!");

You can also set an error at design time. In the Properties window, you will see that once you add an ErrorProvider control to your form, each control has a new property named Error on x where x is the name of the ErrorProvider. You can set this property to a value in the Properties window. If a value is set for the error, the control immediately shows an error at run time.

Different properties of the ErrorProvider component affect how the information is displayed to the user. The Icon property controls which icon is displayed next to the control. You might want to have multiple error providers on a single form one that reports errors and one that reports warnings. You could use different icons for each to provide visual cues to the user. Another property is the BlinkStyle property. This property determines whether the error icon blinks when displayed. The BlinkRate property determines how rapidly the icon blinks.

To create a validation handler that uses the ErrorProvider component

  1. Create your form, and add an ErrorProvider component. The ErrorProvider component appears in the component tray.

  2. Set the CausesValidation property of the control for which you want to provide errors to true if it is not true already.

  3. In the event handler for that control s Validating event, test the value. Use the SetError method to set the error to be displayed when an error condition occurs. The following code demonstrates a validation handler for a text box named pswordTextBox and an error provider named myErrorProvider:

    Visual Basic .NET

    Private Sub pswordTextBox_Validating(ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) _ Handles pswordTextBox.Validating ' Validate the entry If pswordTextBox.Text = "" Then ' Set the error for an invalid entry myErrorProvider.SetError(pswordTextBox, _  "Password cannot be blank!") Else ' Clear the error for a valid entry-no error will be displayed myErrorProvider.SetError(pswordTextBox, "") End If End Sub

    Visual C#

    private void pswordTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e) { // Validate the entry if (pswordTextBox.Text == "") // Set the error for an invalid entry myErrorProvider.SetError(pswordTextBox,  "Password cannot be blank!"); else // Clear the error for a valid entry-no error will be displayed myErrorProvider.SetError(pswordTextBox, ""); }

Lesson Summary

  • Form-level validation validates all fields on a form simultaneously. Field-level validation validates each field as data is entered. Field-level validation provides a finer level of validation control.

  • The TextBox control contains several properties that restrict the values users can enter. These include

    • MaxLength

    • PasswordChar

    • ReadOnly

    • MultiLine

  • Keyboard events allow you to validate keystrokes; these events are raised by the control that has the focus and is receiving input. The form also raises these events when the KeyPreview property is set to true. These events are

    • KeyDown

    • KeyUp

    • KeyPress

  • The Char structure contains several static methods that are useful for validating character input. These methods are

    • Char.IsDigit

    • Char.IsLetter

    • Char.IsLetterOrDigit

    • Char.IsPunctuation

    • Char.IsLower

    • Char.IsUpper

  • The Validating event occurs before the control loses focus and should be used to validate user input. This event occurs only when the CausesValidation property of the control that is about to receive the focus is set to true. To keep the focus from moving away from the control in the Validating event handler, set the CancelEventArgs.Cancel property to true in the event handler.

  • The ErrorProvider component allows you to set an error for a control at run time that displays a visual cue and an informative message to the user. To display an error at run time, use the ErrorProvider.SetError method.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

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