string 我只想在 vb.net 上的文本框中接受信件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14161634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:46:42  来源:igfitidea点击:

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

vb.netstringvalidationtextboxcharacter

提问by user1944225

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

我一直在尝试这样做,所以文本框只接受字母,但验证不起作用。即使我输入数字,它也会处理它并显示“Thankyou for your details”的第一个 lblError,它实际上应该是“Enter A Valid Name”。对于此类问题,他们的验证测试是否类似于 IsNumeric?请帮忙

    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.

我需要简单的方法,没有 [a-zA-Z0-9] 或 RegEx 模式,因为我研究了这些,但我不能使用它们。

Thankyou

谢谢

回答by I kiet

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."

您可以检查文本字符串,即 textbox1.text,以确保它在 .Leave 事件中除了字母字符之外没有任何内容。例如,当用户切换到下一个控件时,这将捕获错误。您可以使用正则表达式执行此操作(在本示例中导入 System.Text.RegularExpressions),或者您可以“手动”检查文本。

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.

如果您想在按下非 alpha 键后立即停止用户,您可以使用 TextChanged 事件而不是 .Leave 事件。

回答by Chris

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.lengththe 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.

这通过从字符串中删除所有大写和小写字母来工作 - 留下任何其他内容。如果我们看到stringname.length删除完成后字符串有多长,并且发现数字为零,则验证通过。但是,如果数字大于零,则我们的字符串包含非字母字符。

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

回答by sjkp

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

回答by Bayriss

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

这应该有助于它应该适用于任何其他文本输入,例如输入框(peudo)

enter code here 

textbox1.textchanged

textbox1.textchanged

Dim check, check2 as Boolean

Dim check,check2 为布尔值

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

check = textbox1.text like " [A-Za-z]" ' 检查字母 check2 = textbox1.text like "[0-9]" ' 检查不是字母

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

如果 check = true 且 check2 = false 则附加文本 elseif check = false 或 check2 = true 然后不附加文本

hope it helps

希望能帮助到你

回答by Deep

Can't you use ASCII Characters? Like this:

你不能使用 ASCII 字符吗?像这样:

(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

如果您不需要允许“_”下划线,则删除“ Or Asc(e.KeyChar) = 95”,您可以轻松完成此操作。你应该看ASCII字符表自己做。你可以在这里查看表格

回答by Tom Blodget

First, you should note that you are using Unicode.

首先,您应该注意您使用的是 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.

其次,Unicode 很复杂。特别是,.NET 字符串使用 UTF-16 代码单元,其中一个或两个编码一个代码点。此外,一些代码点是“组合字符”——它们不能独立存在,但经常单独出现或在字母后多次出现。

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.

下面是验证逻辑。它遍历字符串并检查每个文本元素(又名字素)的第一个代码点是否是一个 Unicode 字母。

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.

顺便说一句——你对什么是名字的看法非常狭隘。我投入了一个空间来打破一个误解;这是一个明显的案例。但是,总的来说,我不想告诉用户我认为他们的名字无效。