简体   繁体   中英

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

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

You can check the text string, ie, 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.

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

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

This should help it should work for any other text inputs, such as input boxes (peudo)

enter code here 

textbox1.textchanged

Dim check, check2 as Boolean

check = textbox1.text like " [A-Za-z]" ' checks for letters check2 = textbox1.text like " [0-9]" ' checks for not letters

if check = true and check2 = false then append text elseif check = false or check2 = true then dont append text

hope it helps

Can't you use ASCII Characters? Like this:

(on keypress event)

If Asc(e.KeyChar) <> 8 Then
  If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 122 Then
  ' from 65 to 90 A - Z String is allowed ( Uppercase letter )
  ' from 97 to 122 a - z String is allowed ( Lowercase letter )
    If Asc(e.KeyChar) > 97 Or Asc(e.KeyChar) < 91 Or Asc(e.KeyChar) = 95 Then
  ' As we dont need to include letters between 91-96 we add this code. 
  ' ASCII CHARACTER 95 is Underscore Character.  so we add this manually.

      e.Handled = True

    End If
  End If
End If

If you Dont need to allow "_" underscore then remove the " Or Asc(e.KeyChar) = 95 " You can do this easily. you should watch the ASCII Character Table to do it yourself. You can view table HERE

First, you should note that you are using Unicode.

Second, Unicode is complicated. In particular, .NET Strings use UTF-16 code units, one or two of which encode a codepoint. Also, some codepoints are "combining characters"—they can't stand on their own but often appear singly or in multiplies after letters.

Below is validation logic. It goes through the string and checks that the first codepoint of each text element (aka grapheme) is a Unicode letter.

Dim input = "ØysteinRene"+ Char.ConvertFromUtf32(&H301) +"e Galois" 
'COMBINING ACUTE ACCENT' (U+0301)
Dim etor = System.Globalization.StringInfo.GetTextElementEnumerator(input)
While (etor.MoveNext()) 
    Dim grapheme = etor.GetTextElement()
    ' check the first codepoint in the grapheme 
    ' (others will only be "combining characters")
    If Not Char.IsLetter(grapheme,0) Then 
        Throw New Exception("Your input doesn't match my idea of a name at """  _
                             + grapheme + """")
    End If
End While

BTW—You have a very narrow view of what a name is. I threw in a space to break one misconception; That's an obvious case. But, in general, I wouldn't like to tell users that I consider their name to be invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM