validate a textbox in vb.net

后端 未结 3 805
误落风尘
误落风尘 2021-01-22 10:43

How could i validate a textbox in vb.net, so that it gives error message if i enter anything apart from alphabets

3条回答
  •  时光说笑
    2021-01-22 11:38

    You can check the text string, i.e., textbox1.text, to make sure it has nothing besides alphabet characters in the .Leave event. This will catch an error when the user tabs to the next control, for example. You can do this using a regular expression (import System.Text.RegularExpressions for this example), or you can check the text "manually."

    Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
      If Not Regex.Match(TextBox1.Text, "^[a-z]*$", RegexOptions.IgnoreCase).Success Then
        MsgBox("Please enter alpha text only.")
        TextBox1.Focus()
      End If
    End Sub
    

    If you want to stop the user as soon as a non-alpha key is pressed, you can use the TextChanged event instead of the .Leave event.

提交回复
热议问题