I only want letter to be accepted into the textbox on vb.net

32,285

Solution 1

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.

Solution 2

Regex is the cleanest way of doing this. However you asked for the long way...

This works by removing all upper and lowercase letters from a string - leaving behind anything else. If we then see how long stringname.length the string is after the removal has completed, and find the number is zero then the validation has passed. However if the number is greater than zero, then our string contained non alphabet characters.

If (TextBox1.Text <> "") Then

    Dim userInput As String = TextBox1.Text
    Dim filteredUserInput As String = userInput

    Dim listOfLetters As String() = New String() {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
    ' go through each letter in the 'listOfLetters' array and replace that letter with.. nothing
    For Each letter In listOfLetters
        filteredUserInput = Replace(filteredUserInput, letter, "")
    Next

    ' now we have done the work - count how many characters are left in the string, if it is more than 0 we have invalid characters
    If (filteredUserInput <> "") Then
        MsgBox("This failed validation, contains invalid chars (" + Str(filteredUserInput.Length) + ")")
    Else
        MsgBox("This passed validation")
    End If

End If

Or if you want it function-ified..

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    If (TextBox1.Text <> "") Then

        Dim userInput As String = TextBox1.Text
        ' if the 'isThisAValidString()' returns true then it is a valid (and has not faild validation) a-zA-Z
        If (isThisAValidString(userInput) = True) Then
            MsgBox("This is valid")
        Else
            MsgBox("This is not valid")
        End If

    End If

End Sub

Function isThisAValidString(input As String)

    Dim userInput As String = input
    Dim filteredUserInput As String = userInput

    Dim listOfLetters As String() = New String() {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
    ' go through each letter in the 'listOfLetters' array and replace that letter with.. nothing
    For Each letter In listOfLetters
        filteredUserInput = Replace(filteredUserInput, letter, "")
    Next

    ' now we have done the work - count how many characters are left in the string, if it is more than 0 we have invalid characters
    If (filteredUserInput <> "") Then
        ' this failed!
        Return False
    Else
        'this passed
        Return True
    End If

End Function

Solution 3

Why not regex? It's the right tool for the job, unless you are leaving something out of your questions.

You can build a array of all english letters like this (it's uppercase) then you can check if all characters in the name is in the array.

Private Shared Function IsLetters(s As String) As Boolean
    For Each c As Char In s.ToUpper().ToCharArray()
        If Not onlyLetters().Contains(c) Then
            Return False
        End If
    Next
    Return True
End Function

Private Shared Function onlyLetters() As Char()
    Dim strs = New List(Of Char)()
    Dim o As Char = "A"C
    For i As Integer = 0 To 25
        strs.Add(Convert.ToChar(o + i))
    Next

    Return strs.ToArray()
End Function
Share:
32,285
user1944225
Author by

user1944225

Updated on July 06, 2022

Comments

  • user1944225
    user1944225 almost 2 years

    Ive been trying to do this, so the textbox only accepts letters, but the validation does not work. Even when I enter numbers it processes it and shows the first lblError of "Thankyou for your details", where it should actually be "Enter A Valid Name ". is their are validation test similar to IsNumeric for this type of problem? plz help

        Dim MyName As String
        If txtMyName.Text Then
            MyName = txtMyName.Text
            lblError.Text = "Thankyou for your details"
        Else
            lblError.Text = "Enter A Valid Name "
    
        End If
    
    End Sub
    

    End Class

    And I need simple methods, nothing with [a-zA-Z0-9], or RegEx patterns, as ive researched these and I cannot use them.

    Thankyou

    • Fermin
      Fermin over 11 years
      This looks like a homework assignment. Are you looking for a way to stop the user entering them, if so look at events. If you want to validate it after they have entered one way could be to check each character individually and see if it is a number.
    • Alexan
      Alexan over 11 years
      maybe just use RegularExpressionValidator: msdn.microsoft.com/en-us/library/…
    • user1944225
      user1944225 over 11 years
      Thanks, but this isnt a homework assignment, im just learning about vb.net for myself and starting at the basics,
    • Chris
      Chris over 11 years
      The basics are that to match a strinh of letters a regex is the best way. I dont know of any isStringLetters built in. The reason we are all saying regex is because it is the best way we know (plus the least lines of code
  • user1944225
    user1944225 over 11 years
    I cant use thinks like regex because i havent learned it yet, so i need to stick to simple valiadation
  • user1944225
    user1944225 over 11 years
    @Chris, Thanks but you have used regex, is their any way of validating it without using regex?
  • user1944225
    user1944225 over 11 years
    Thanks for this answer, but what is the long war around?
  • user1944225
    user1944225 over 11 years
    Do you now the simple validation route?
  • Chris
    Chris over 11 years
    You could cycle through each letter in a string, checking it's char() number against a preset range. Each letter upper and lower case have a unique number allocated to them so checking that will work. BUT I doubt it will be very quick if you are comparing loads of long strings
  • Chris
    Chris over 11 years
    I have changed my code above to reflect your long way around request