user2275365
user2275365

Reputation: 23

Validate user input in a TextBox

User provides value in txtAmount TextBox that I later process this way:

c = txtAmount.Text 'GET AN ERROR HERE BECAUSE I NEED C TO BE AN  INT

I want a user to be able to correct entered value, so I can get c as an integer:

If Not (IsNumeric(txtAmount.Text)) Then
  lblMsg.Caption = " Please enter you answer numericly "
  txtAmount.Text = ""
  txtAmount.SetFocus 'HERE IS WHAT I WANT TO FIX
End If
If (txtAmount.Text = "") Then
  lblMsg.Caption = " Please enter amount to convert"
  txtAmount.SetFocus
End If

Where should I place my validation code so its called before I process entered value?

Upvotes: 1

Views: 12852

Answers (4)

Jithin
Jithin

Reputation: 19

you can enter the statements in the validation event of a text box control. while entering in the box it automatically validates the data in the text box so it can be identified the data inserted

Upvotes: 0

godspeed
godspeed

Reputation: 1

Private Sub txtName_Validate(Cancel As Boolean)
   If txtName.Text = "" Then
      MsgBox "Please enter your name!", vbExclamation, ""
      Cancel = True
   End If
End Sub

When the Cancel parameter is True, the input focus goes back to the txtName control.

Private Sub txtPhone_Validate(Cancel As Boolean)
   If Len(txtPhone.Text) < 10 Then
      MsgBox "Enter the phone number in 10 digits!", vbExclamation, ""
      Cancel = True
   End If
End Sub

In this case, the input focus moves back to the txtPhone control when the Cancel parameter is set to True.

Upvotes: 0

Balbo
Balbo

Reputation: 85

You can choose to validate it while typing. To do it use the change event like this:

Private Sub txtAmount_Change()

    On Error GoTo ErrManag

    If txtAmount.Text = "" Then Exit Sub
    If Not ((CInt(txtAmount.Text) >= 0) And (CInt(txtAmount.Text) <= 10)) Then MsgBox " Some max-min-error message"

ErrManag:

    If Err.Description <> "" Then
        MsgBox Err.Description 'This will prompt the error if a char is inserted
    End If

End Sub

In this example the user will have the opportunity to correct it, but if he doesn't you have to recheck it later when clicking the "Send" button like Hrqls suggested.

Upvotes: 1

Hrqls
Hrqls

Reputation: 2951

Below is a sample project to show what I mean:

'1 form with:
'  1 textbox: name=Text1
Option Explicit

Private Sub Text1_KeyPress(KeyAscii As Integer)
  KeyAscii = NrOnly(KeyAscii)
End Sub

Private Function NrOnly(intKey As Integer) As Integer
  Dim intReturn As Integer
  intReturn = intKey
  Select Case intKey
    Case vbKeyBack        'allow backspace
    Case vbKey0 To vbKey9 'allow numbers 0 to 9
    Case Else             'block all other input
      intReturn = 0
  End Select
  NrOnly = intReturn
End Function

Upvotes: 1

Related Questions