Link to home
Start Free TrialLog in
Avatar of rrowe68
rrowe68

asked on

Number Validation in Text Boxes

What is the simplest way to do number validation in a text box.

I have a form with 30+ textboxes on it.   Only half need number validation.    Is there a way to do this a the form level or does each control need to be validated.   Is this done on the 'Leave' event?  What code snippit would you suggest?

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of pollock_d
pollock_d

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pollock_d
pollock_d

Oh, i would create my own custom number textbox that inherits from textbox... and just use that for each textbox that needs validating....
Here is an example for you.
You didn't specify if the text boxes are individual, or created as a control array so I did it both ways.

If you have any questions let me know.

Thanks
Roger
Private Sub Text1_KeyPress(KeyAscii As Integer)
    'This will display the value in the form's caption.
    Me.Caption = KeyAscii
        
    If KeyAscii >= 48 And KeyAscii <= 57 Then
        'The user pressed 0 1 2 3 4 5 6 7 8 9
    Else
        'The user pressed a Non-Numeric Key
        Keyascii = 0 'Don't Allow
    End If
    
    ''''''''''''
    '    Or    '
    ''''''''''''
    
    Select Case KeyAscii
        Case 48 To 57
            'The User Pressed 0..9
        
        Case 13
            'If you don't like the beep
            'When the user presses Enter:
            SendKeys vbTab
            KeyAscii = 0
        Case Else
            'Anything special you want processed
            Keyascii = 0 'Don't Allow
    End Select
End Sub
 
Private Sub Text2_KeyPress(Index As Integer, KeyAscii As Integer)
    
    'Each textbox will have an index number.
    'The first  textbox will have an index nunber of 0
    'The second textbox will have an index nunber of 1 ... etc
    
    'This will display the value in the form's caption.
    Me.Caption = "Textbox Index (" & Index & ")'s Value = " & KeyAscii
    
    Select Case Index
        Case 0 To 3
            'The First 4 textboxes
            If KeyAscii >= 48 And KeyAscii <= 57 Then
                'The user pressed 0 1 2 3 4 5 6 7 8 9
            Else
                'The user pressed a Non-Numeric Key
                Keyascii = 0 'Don't Allow
            End If
            
        Case 7
            'The 8th Textbox
            If KeyAscii >= 48 And KeyAscii <= 57 Then
                'The user pressed 0 1 2 3 4 5 6 7 8 9
            Else
                'The user pressed a Non-Numeric Key
                Keyascii = 0 'Don't Allow
            End If
    End Select
End Sub

Open in new window

Hello rrowe68,

What are you using as the source of your textboxes on your form?  Is it a DataSet or DataTable?  If it is, then you can validate the data for the columns and display errors if necessary.

Regards,

VBRocks