正则表达式是最干净的方法。但是你问了很长的路...
这通过从字符串中删除所有大写和小写字母来工作 - 留下任何其他内容。如果我们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
或者如果你想要它功能化..
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