user161004
user161004

Reputation: 985

validate a textbox in vb.net

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

Upvotes: 2

Views: 19116

Answers (3)

Hans Olsson
Hans Olsson

Reputation: 55009

If it's a standard textbox in a WinForms app you can validate every typed character by handling the KeyPressed event and have the following code in the event handler:

e.Handled = Not Char.IsLetter(e.KeyChar)

The user could still use the mouse to paste something in there though so you might need to handle that as well.

Another option is to handle the Validating event and if the textbox contains any non alphabetic characters you set e.Cancel to true.

Upvotes: 1

xpda
xpda

Reputation: 15813

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.

Upvotes: 3

Brian David Berman
Brian David Berman

Reputation: 7684

CustomFieldValidator with a regex.

Upvotes: 1

Related Questions