home account info subscribe login search FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Advanced Visual Basic Techniques
(Publisher: John Wiley & Sons, Inc.)
Author(s): Rod Stephens
ISBN: 0471188816
Publication Date: 06/01/97

Search this book:
 
Previous Table of Contents Next


Validating Data

Another important type of feedback an application can give the user is field validation. For example, the application can prevent the user from entering letters in a numeric text field. If the user tries to enter a letter, the application beeps and then discards the character. This signal tells the user that the character is not allowed.

By presenting this feedback as soon as the user types an invalid character, the application prevents problems later. If the user successfully entered a letter into this field, the program would later be unable to convert the text into a number. At that point the application would be forced to tell the user that the input is invalid and the user would need to enter a new value. By this time, the user would probably have left this field and moved on to other things. To enter a new value, the user would need to shift context mentally, reexamine the old field, figure out why the current value is invalid, and enter a new value. The user may even need to refer to notes that were readily available earlier. It is much easier on the user if the program refuses the incorrect data in the first place.

There are times when invalidating the user’s input and beeping is very annoying. If the field requires an obscure pattern of characters, the user may become frustrated trying to figure out what to enter. In this case it is essential that the application provide help that explains the field’s format. The best way to do this is by using context-sensitive help. The user can press F1 to activate the context-sensitive help for the field and learn exactly what value is required.

Field validation is also frustrating if it prevents the user from leaving the field. A program could use a field’s LostFocus event handler to check the field’s value. If the value was invalid, the program could beep and use the SetFocus method to move the input focus back to the field. If the user cannot figure out what form of input the field requires, the program could trap the user there forever. Even a user who knows what kind of input is required will sometimes want to move on and come back to fill the field in later. To make this possible, applications should not use SetFocus in LostFocus event handlers.

Visual Basic itself provides very little support for field validation. You can set a text field’s MaxLength property to indicate how many characters the user can enter, but many fields require more sophisticated validation.

ExpenseReporter uses several different types of field validations that all follow a similar pattern. Each field’s KeyDown and KeyPress event handlers invoke routines in the Visual Basic module Fields.BAS. These routines determine whether the new key will make the field’s value invalid. If so, the routine beeps and discards the key.

For example, ExpenseReporter’s AdvanceText field allows the user to enter only a dollar amount. The following code shows this field’s KeyDown and KeyPress event handlers.

Private Sub AdvanceText_KeyDown(KeyCode As Integer, Shift As Integer)
    ValidateMoney_KeyDown AdvanceText, KeyCode
End Sub

Private Sub AdvanceText_KeyPress(KeyAscii As Integer)
    ValidateMoney_KeyPress AdvanceText, KeyAscii
End Sub

The ValidateMoney_KeyDown subroutine checks to see if the user pressed the Delete key. If so, it invokes the same ValidateMoney_KeyPress routine called by the field’s KeyPress event handler. ValidateMoney_KeyDown ignores all keys except the Delete key because those keys are handled by the KeyPress event handler.

Public Sub ValidateMoney_KeyDown(ctl As TextBox, key As Integer)
Dim newkey As Integer

    ‘ Only bother for vbKeyDelete. All others are
    ‘ handled in the KeyPress event handler.
    If key = vbKeyDelete Then
        newkey = KEY_DELETE
        ValidateMoney_KeyPress ctl, newkey

        ‘ If the routine rejected newkey, reject
        ‘ the original key.
        If newkey = 0 Then key = 0
    End If
End Sub

ValidateMoney_KeyPress first uses the function NewValue to determine the new value the field will have if the key is allowed. It then uses function ValidMoney to decide if the result is in a valid dollar format.

Public Sub ValidateMoney_KeyPress(ctl As TextBox, key As Integer)
Dim txt As String

    txt = NewValue(ctl, key)
    If Not ValidMoney(txt) Then
        Beep
        key = 0
    End If
End Sub

The NewValue function must deal with several possibilities. The new key might be an ordinary keyboard key such as A or 7. The new key might be a special key such as Delete or Backspace. It could even be an unusual key like Ctrl-V, which copies the current clipboard selection into the field.

When the user presses a key, the new text will replace whatever text is currently highlighted in the field. The highlighted text begins at the position given by the field’s SelStart property and is SelLength characters long. If no text is highlighted, the new text is inserted at the location given by SelStart.

Notice how the following code uses the Clipboard object’s GetText function to decide what text to insert if the user pressed Ctrl-V.

Public Function NewValue(ctl As TextBox, key As Integer) As String
Dim txt As String
Dim start As Integer
Dim length As Integer
Dim length3 As Integer
Dim txt1 As String
Dim txt2 As String
Dim txt3 As String

    txt = ctl.Text

    If (key < KEY_MIN Or key > KEY_MAX) And _
        key <> KEY_CTL_V And _
        key <> KEY_CTL_X And _
        key <> KEY_DELETE And _
        key <> vbKeyReturn And _
        key <> vbKeyBack _
    Then
        ‘It’s an unknown nonvisible key like ^C.
        ‘ Assume it will not change the text.
        NewValue = txt
        Exit Function
    End If

    start = ctl.SelStart
    length = ctl.SelLength

    ‘ Calculate the first part of the new text.
    If start < 1 Then
        txt1 = “”
    Else
        txt1 = Left$(txt, start)
    End If

    ‘ Calculate the third part of the new text.
    length3 = Len(txt) - start - length
    If length3 < 1 Then
        txt3 = “”
    Else
        txt3 = Right$(txt, length3)
    End If

    ‘ Calculate the middle part of the new text.
    If key = KEY_CTL_V Then
        txt2 = Clipboard.GetText()
    ElseIf key = KEY_CTL_X Then
        ‘Delete the selected text.
        txt2 = “”
    ElseIf key = KEY_DELETE Then
        If length = 0 And txt3 <> “” Then
            ‘ Delete the character after the
            ‘ insertion point.
            txt3 = Right$(txt3, Len(txt3) - 1)
        Else
            txt2 = “”
        End If
    ElseIf key = vbKeyBack Then
        If length = 0 And txt1 <> “” Then
            ‘ Delete the character before the
            ‘ insertion point.
            txt1 = Left$(txt1, Len(txt1) - 1)
        Else
            txt2 = “”
        End If
    Else
        ‘It’s a return or printable character.
        txt2 = Chr$(key)
    End If

    NewValue = txt1 & txt2 & txt3
End Function


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.