Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitlePerform field- and form-level validations
Keywordsfield, form, validation
CategoriesSoftware Engineering, Database
 
Perform field-level validations in the TextBox's (or other controls') LostFocus event handlers. If a value is invalid, highlight the field but do not force the user to correct it yet. That can be very annoying and slows the user down while typing in many fields.

When the user clicks the Ok button, perform field- and form-level edits and require the user to fix any problems.

 
' Reset the field's colors.
Private Sub NumericText_GotFocus()
    SetValid NumericText
End Sub

' Make sure the data passes edits.
Private Sub NumericText_LostFocus()
    If FailsNumeric(NumericText.Text) Then _
        SetInvalid NumericText
End Sub

' Set the control's colors for a valid field.
Private Sub SetValid(ctl As TextBox)
    ctl.ForeColor = GoodLabel.ForeColor
    ctl.BackColor = GoodLabel.BackColor
End Sub

' Set the control's colors for an invalid field.
Private Sub SetInvalid(ctl As TextBox)
    ctl.ForeColor = BadLabel.ForeColor
    ctl.BackColor = BadLabel.BackColor
End Sub

' Return true if the field fails its edits.
Function FailsNumeric(txt As String) As Boolean
Dim ch As String
Dim i As Integer

    FailsNumeric = True
    
    For i = 1 To Len(txt)
        ch = Mid$(txt, i, 1)
        If ch < "0" Or ch > "9" Then Exit Function
    Next i
    FailsNumeric = False
End Function

Private Sub CmdOk_Click()
    ' Perform form-level validations.
    If FailsAlpha(AlphaText.Text) Then
        MsgBox "AlphaText must be alphabetic."
        AlphaText.SetFocus
        Exit Sub
    End If
    
    If FailsNumeric(NumericText.Text) Then
        MsgBox "NumericText must be numeric."
        NumericText.SetFocus
        Exit Sub
    End If
    
    If FailsNumeric(Numeric2Text.Text) Then
        MsgBox "Numeric2Text must be numeric."
        Numeric2Text.SetFocus
        Exit Sub
    End If
    If Numeric2Text.Text <> NumericText.Text Then
        MsgBox "Numeric2Text must match NumericText."
        Numeric2Text.SetFocus
        Exit Sub
    End If
        
    If FailsOdd(OddText.Text) Then
        MsgBox "OddText must be odd."
        OddText.SetFocus
        Exit Sub
    End If
        
    If FailsEven(EvenText.Text) Then
        MsgBox "EvenText must be even."
        EvenText.SetFocus
        Exit Sub
    End If

    MsgBox "All edits passed."
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated