Home > Articles > Microsoft > Other Microsoft

  • Print
  • + Share This
This chapter is from the book

User Input Validation

Validate user input.

It's a truism of the computer world that garbage-in is garbage-out. When designing an application that interacts with the user to accept data, you must ensure that the entered data is acceptable to the application. The most obvious time to ensure the validity of data is at the time of data entry itself. You can use various techniques for validating data, including these:

  • Restrict the values that a field can accept by using standard controls like combo boxes, list boxes, radio buttons and check boxes. These allow users to select from a set of given values rather than permitting free keyboard entry.

  • Capture the user's keystrokes and analyze them for validity. Some fields might require the user to enter only alphabetic values but no numeric values or special characters; in that case, you can accept the keystrokes for alphabetic characters while rejecting others.

  • Restrict entry in some data fields by enabling or disabling them depending on the state of other fields.

  • Analyze the contents of the data field as a whole and warn the user of any incorrect values when the user attempts to leave the field or close the window.

You saw how to use the various controls to limit input in Chapter 2, "Controls." I'll cover the rest of the techniques in this section.

Keystroke-Level Validation

When you press a key on a control, three events take place in the following order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

You can add code to the event handlers for these events to perform keystroke-level validation. You will choose which event to handle based on the order in which the events are fired and the information passed in the event argument of the event handler.

The KeyPress event happens after the KeyDown event but before the KeyUp event. Its event handler receives an argument of type KeyPressEventArgs. Table 3.4 lists the properties of the KeyPressEventArgs class.

Table 3.4 Important Properties of the KeyPressEventArgs Class

Property

Description

Handled

Setting this property to True indicates that the event has been handled.

KeyChar

Gets the character value corresponding to the key.


The KeyPress event only fires if the key pressed generates a character value. This means you won't get a KeyPress event from keys such as function keys, control keys, and the cursor movement keys; you must use the KeyDown and KeyUp events to trap those keys.

The KeyDown and KeyUp events occur when a user presses and releases a key on the keyboard. The event handlers of these events receive an argument of the KeyEventArgs type; this argument provides the properties listed in Table 3.5.

Table 3.5 Important Properties of the KeyEventArgs Class

Property

Description

Alt

Returns True if Alt key is pressed, otherwise False.

Control

Returns True if Ctrl key is pressed, otherwise False.

Handled

Indicates whether the event has been handled.

KeyCode

Gets the keyboard code for the event. Its value is one of the values specified in the Keys enumeration.

KeyData

Gets 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

Gets an integer representation of the KeyData property.

Modifiers

Gets the modifier flags that indicate which combination of modifier keys (Ctrl, Shift, and Alt) were pressed.

Shift

Returns True if Shift key is pressed, otherwise False.


The KeyPreview Property

By default, only the active control will receive keystroke events. The Form object also has KeyPress, KeyUp, and KeyDown events, but they are fired only when all the controls on the form are either hidden or disabled. However, you can modify this behavior.

When you set the KeyPreview property of a form to True, the form will receive all three events (KeyDown, KeyPress, and KeyUp) just before the active control receives them. This allows you to set up a two-tier validation on controls. If you want to discard a certain type of characters at the form level itself, you can set the Handled property for the event argument to True (This will not allow the event to propagate to the active control.); otherwise, the events will propagate to the active control. You can then use keystroke events at the control level to perform field-specific validation such as restricting the field to only numeric digits.

Field-Level Validation

Field-level validation ensures that the value entered in the field as a whole is in accordance with the application's requirement. If it isn't, you can alert the user to the problem. Appropriate times to perform field-level validations are

  • When the user attempts to leave the field.

  • When the content of the field changes for any reason. This isn't always a feasible strategy. For example, if you're validating a date to be formatted as "mm/dd/yy", it won't be in that format until all the keystrokes are entered.

When a user enters and leaves a field, events occur in the following order:

  1. Enter

  2. GotFocus

  3. Leave

  4. Validating

  5. Validated

  6. LostFocus

The Validating Event

The Validating event is the ideal place for performing field-level validation logic on a control. The event handler for the Validating event receives an argument of type CancelEventArgs. Its only property is the Cancel property. When set to True, this property cancels the event.

Inside the Validating event, you can write code to

  • Programmatically correct any errors or omissions made by the user.

  • Show error messages and alerts to the user so that he can fix the problem.

Inside the Validating event, you might also want to retain the focus in the current control, thus forcing user to fix the problem before proceeding further. You can use either of the following techniques to do this:

  • Use the Focus method of the control to transfer the focus back to the field.

  • Set the Cancel property of the CancelEventArgs object to True. This will cancel the Validating event, leaving the focus in the control.

A related event is the Validated event. The Validated event is fired just after the Validating event and enables you to take actions after the control's contents have been validated.

The CausesValidation Property

When you use the Validating event to retain the focus in a control by canceling the event, you must also consider that you are making your control sticky.

Consider what can happen if you force the user to remain in a control until the contents of that control are successfully validated. Now when the user clicks on the Help button in the toolbar to see what is wrong, nothing will happen unless the user makes a correct entry. This can be an annoying situation for users and one that you want to avoid in your application.

NOTE

Validating Event and Sticky Forms The Validating event also fires when you close a form. If you set the Cancel property of the CancelEventArgs object to True inside this event, it will cancel the close operation as well.

This problem has a work-around: Inside the Validating event you should set the Cancel property of CancelEventArgs argument to True only if the mouse pointer is in the form's Client area. The close box is in the title bar outside the client Area of form. Therefore, when the user clicks the close box, the Cancel property will not be set to True.

The CausesValidation property comes to your rescue here. The default value of the CausesValidation property for any control is True, meaning that the Validating event will fire for any control requiring validation before the control in question receives focus.

When you want a control to respond irrespective of the validation status of other controls, set the CausesValidation property of that control to False. So in the previous example, the Help button in the toolbar should have its CausesValidation property set to False.

ErrorProvider

The ErrorProvider component in the Visual Studio .Net toolbox is useful when showing validation-related error messages to the user. The ErrorProvider component can display a small icon next to a field when the field contains an error. When the user hovers the mouse pointer over the icon, it also displays an error message as a ToolTip. This is a better way of displaying error messages as compared to the old way of using message boxes because it eliminates at least two serious problems with message boxes:

  • If you have errors in multiple controls, several message boxes popping up simultaneously can annoy or scare users.

  • After the user dismisses a message box, the error message is no longer available for reference.

Table 3.6 lists some important members of the ErrorProvider class that you should be familiar with.

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 a control. The icon is displayed only when an error description string has been set for the control.

SetError

Method

Sets the error description string for the specified control.

SetIconAlignment

Method

Sets the location to place an error icon with respect to the control. It has one of the ErrorIconAlignment values.

SetIconPadding

Method

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


The ErrorProvider object displays an error icon next to a field when you set the error message string. The error message string is set by the SetError method. If the error message is empty, no error icon is displayed and the field is considered to be correct. You'll see how to use the ErrorProvider component in Step By Step 3.6.

STEP BY STEP 3.6 Using the ErrorProvider Control and Other Validation Techniques

  1. Add a new Windows Form to your Visual Basic .NET project.

  2. Place three TextBox controls (txtMiles, txtGallons, and txtEfficiency) and a Button (btnCalculate) on the form's surface and arrange them as was shown in Figure 3.1. Add the label controls as necessary.

  3. Add an ErrorProvider (ErrorProvider1) control to the form. The ErrorProvider control will be displayed in the component tray.

  4. Double-click the form and add the following code to handle the form's Load event:

    Private Sub StepByStep3_6_Load( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles MyBase.Load
      ' Set the ErrorProvider's Icon 
      ' alignment for the textbox controls
      ErrorProvider1.SetIconAlignment( _
       txtMiles, ErrorIconAlignment.MiddleLeft)
      ErrorProvider1.SetIconAlignment( _
       txtGallons, ErrorIconAlignment.MiddleLeft)

    End Sub

  5. Add code to handle the Validating events of the txtMiles and txtGallons controls:

    Private Sub txtMiles_Validating(ByVal sender As Object, _
     ByVal e As System.ComponentModel.CancelEventArgs) _
     Handles txtMiles.Validating
      Try
        Dim decMiles As Decimal = _
         Convert.ToDecimal(txtMiles.Text)
        ErrorProvider1.SetError(txtMiles, "")
      Catch ex As Exception
        ErrorProvider1.SetError(txtMiles, ex.Message)
      End Try
    End Sub
    
    Private Sub txtGallons_Validating(ByVal sender As Object, _
     ByVal e As System.ComponentModel.CancelEventArgs) _
     Handles txtGallons.Validating
      Try
        Dim decGallons As Decimal = _
         Convert.ToDecimal(txtGallons.Text)
        If (decGallons > 0) Then
          ErrorProvider1.SetError(txtGallons, "")
        Else
          ErrorProvider1.SetError(txtGallons, _
           "Please enter a positive non-zero value")
        End If
      Catch ex As Exception
        ErrorProvider1.SetError(txtGallons, ex.Message)
      End Try

    End Sub

  6. Add the following code to the Click event handler of btnCalculate:

    Private Sub btnCalculate_Click( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnCalculate.Click
      ' Check whether the error description is not empty 
      'for either of the textbox controls 
      If (ErrorProvider1.GetError(txtMiles) <> "") Or _
       (ErrorProvider1.GetError(txtGallons) <> "") Then
        Exit Sub
      End If
      Try
        Dim decMiles As Decimal = _
         Convert.ToDecimal(txtMiles.Text)
        Dim decGallons As Decimal = _
         Convert.ToDecimal(txtGallons.Text)
        Dim decEfficiency As Decimal = decMiles / decGallons
        txtEfficiency.Text = _
         String.Format("{0:n}", decEfficiency)
      Catch ex As Exception
        Dim msg As String = _
         String.Format("Message: {0}" & vbCrLf & _
         "Stack Trace:" & vbCrLf & "{1}", _
         ex.Message, ex.StackTrace)
        MessageBox.Show(msg, ex.GetType().ToString())
      End Try

    End Sub

  7. Set the form as the startup object for the project.

  8. Run the project. Enter values for miles and gallons and run the program. It will calculate the mileage efficiency as expected. You will notice that when you enter an invalid value into any of the TextBox controls, the error icon starts blinking. It will display an error message when the mouse is hovered over the error icon, as shown in Figure 3.11.

Figure 3.11 ErrorProvider control showing the error icon and the error message.

Enabling Controls Based On Input

One of the useful techniques for restricting user input is the selective enabling and disabling of controls. Some common cases in which this is useful are

  • Your application might have a Check Here If You Want to Ship to a Different Location check box. When the user checks the check box, you should allow her to enter values in the fields for a shipping address. Otherwise, the shipping address is same as the billing address.

  • In a Find dialog box, you have two buttons labeled Find and Cancel. You want to keep the Find button disabled initially and enable it only when the user enters some search text in the text box.

The Enabled property for a control is True by default. When you set it to False, the control cannot receive the focus and will appear grayed out.

For some controls, such as the TextBox, you can also use the ReadOnly property to restrict user input. One advantage of using the ReadOnly property is that the control will still be able to receive focus so that users will be able to scroll through the text in the control if it is not completely visible. In addition, users can also select and copy the text to the clipboard if the ReadOnly property is true.

Other Properties for Validation

In addition to already mentioned techniques, the CharacterCasing and MaxLength properties allow you to enforce some restrictions on the user input.

The CharacterCasing Property

The CharacterCasing property of a TextBox control changes the case of characters in the text box as required by your application. For example, you might want to convert all characters entered in a text box used for entering a password to lowercase to avoid case confusion.

This property can be set to CharacterCasing.Lower, CharacterCasing.Normal (the default value) or CharacterCasing.Upper.

The MaxLength Property

The MaxLength property of a TextBox or a ComboBox specifies the maximum number of characters the user can enter into the control. This property comes in handy when you want to restrict the size of some fields such as a telephone number or a ZIP code.

TIP

MaxLength The MaxLength property only affects the text entered into the control interactively by the user. Programmatically, you can set the value of the Text property to a value that is larger than the value specified by the MaxLength property. So you can use the MaxLength property to limit user input without limiting the text that you can programmatically display in the control.

When the MaxLength property is zero (the default), the number of characters that can be entered is limited only by the available memory. In practical terms, this means that the number of characters is generally unlimited.

In Guided Practice Exercise 3.2 you will learn to use some of the validation tools such as the Enabled property, the Focus method of the TextBox control, and the ErrorProvider control.

GUIDED PRACTICE EXERCISE 3.2

In this exercise, your job is to add some features to the keyword searching application you created in Guided Practice Exercise 3.1. The Keyword text box and the Search button should be disabled when the application is launched. These controls should be enabled as the user progresses through the application. The application assumes that the entered keyword must be a single word. If it is not, you must display an error icon and set the error message. The keyword control should not lose focus unless the user enters valid data in the text box.

Try this on your own first. If you get stuck, or would like to see one possible solution, follow these steps:

  1. Add a new form to your Visual Basic .NET Project.

  2. Place three Label controls, two TextBox controls, and two Button controls on the form, arranged as was shown in Figure 3.8. Name the text box for accepting file names txtFileName and the Browse button btnBrowse. Name the text box for accepting keywords txtKeyword and the search button btnSearch. Name the results label lblResult.

  3. Add an OpenFileDialog control to the form and change its name to dlgOpenFile. Add an ErrorProvider (ErrorProvider1) control to the form. The ErrorProvider control will be placed in the component tray.

  4. Double-click the form and add the following code to handle the Form's Load event:

    Private Sub GuidedPracticeExercise3_2_Load( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles MyBase.Load
      ' Disable the Keyword textbox and Search button
      txtKeyword.Enabled = False
      btnSearch.Enabled = False
      ErrorProvider1.SetIconAlignment( _
       txtKeyword, ErrorIconAlignment.MiddleLeft)
    End Sub
  5. Attach TextChanged and Validating event handlers to the txtKeyword control by adding the following code:

    Private Sub txtKeyword_TextChanged(ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles txtKeyword.TextChanged
      If txtKeyword.Text.Length = 0 Then
        btnSearch.Enabled = False
      Else
        btnSearch.Enabled = True
      End If
    End Sub
    
    Private Sub txtKeyword_Validating(ByVal sender As Object, _
     ByVal e As System.ComponentModel.CancelEventArgs) _
     Handles txtKeyword.Validating
      If txtKeyword.Text.Trim().IndexOf(" ") >= 0 Then
        ErrorProvider1.SetError(txtKeyword, _
         "You may only search with a single word")
        txtKeyword.Focus()
        txtKeyword.Select(0, txtKeyword.Text.Length)
      Else
        ErrorProvider1.SetError(txtKeyword, "")
      End If
    End Sub
  6. Create a method named GetKeywordFrequency that accepts a string and returns the number of lines containing it. Add the following code to the method:

    Private Function GetKeywordFrequency( _
     ByVal strPath As String) As Integer
      Dim count As Integer = 0
      If File.Exists(strPath) Then
        Dim sr As StreamReader = _
         New StreamReader(txtFileName.Text)
        Do While (sr.Peek() > -1)
          If sr.ReadLine().IndexOf( _
           txtKeyword.Text) >= 0 Then
            count += 1
          End If
        Loop
      End If
      GetKeywordFrequency = count
    End Function
  7. Add the following code to the Click event handler of the btnBrowse button:

    Private Sub btnBrowse_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnBrowse.Click
      If dlgOpenFile.ShowDialog() = DialogResult.OK Then
        txtFileName.Text = dlgOpenFile.FileName
        txtKeyword.Enabled = True
        txtKeyword.Focus()
      End If
    End Sub
  8. Add the following code to the Click event handler of the btnSearch button:

    Private Sub btnSearch_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnSearch.Click
      If ErrorProvider1.GetError(txtKeyword) <> "" Then
        Exit Sub
      End If
      Try
      lblResult.Text = String.Format( _
       "The keyword: '{0}', found in {1} lines", _
       txtKeyword.Text, _
       GetKeywordFrequency(txtFileName.Text))
      Catch ex As Exception
        Dim msg As string = _
         String.Format("Message:" & vbCrLf & "{0}" & _
         vbCrLf & vbCrLf & "StackTrace:" & vbCrLf & "{1}", _
         ex.Message, ex.StackTrace)
        MessageBox.Show(msg, ex.GetType().ToString())
      End Try
    End Sub
  9. Set the form as the startup object for the project.

  10. Run the project. Note that the Keyword text box and the Search button are disabled. Click the Browse button and select an existing file to enable the Keyword text box. Enter the keyword to search in the file to enable the Search button. Click the Search button. If the keyword entered is in wrong format (if it contains a space), the ErrorProvider control will show the error message and the icon.

  • It is generally a good practice to validate user input at the time of data entry. Thoroughly validated data will result in consistent and correct data stored by the application.

  • When a user presses a key three events are generated: KeyDown, KeyPress, and KeyUp in that order.

  • The Validating event is the ideal place for storing the field-level validation logic for a control.

  • The CausesValidation property specifies whether validation should be performed. If False, the Validating and Validated events are suppressed.

  • The ErrorProvider component in the Visual Studio .Net toolbox shows validation-related error messages to the user.

  • A control cannot receive the focus and appears grayed out if its Enabled property is set to False.

  • + Share This
  • 🔖 Save To Your Account