验证TextBox中的用户输入

时间:2013-04-12 17:15:29

标签: vb6

用户在txtAmount TextBox中提供了值,我后来以这种方式处理:

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

我希望用户能够更正输入的值,因此我可以将c作为整数:

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

在处理输入的值之前,我应该在哪里放置我的验证码?

4 个答案:

答案 0 :(得分:1)

下面是一个展示我的意思的示例项目:

'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

答案 1 :(得分:1)

您可以选择在输入时验证它。 为此,请使用如下更改事件:

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

在这个例子中,用户将有机会纠正它,但如果他没有,你必须在点击Hrqls建议的“发送”按钮后再重新检查。

答案 2 :(得分:0)

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

当Cancel参数为True时,输入焦点将返回txtName控件。

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

在这种情况下,当Cancel参数设置为txtPhone时,输入焦点将移回True控件。

答案 3 :(得分:0)

您可以在文本框控件的验证事件中输入语句。 在输入框时,它会自动验证文本框中的数据,以便可以识别出插入的数据