这当然不是最好的方法,但我不知道你是否会找到最好的方法,因为最好是主观的,而且通常取决于不止一种情况和意见。
假设一个带有名称txtinput
和标签的文本框,您将在其中显示命名的结果lblMessage
并假设您使用的是 ASCII 字符输入:
如果您有以下情况TextChanged
:txtinput
'Check if the length is greater than five, if it is truncate it.
If txtinput.Text.Length > 5 Then
txtinput.Text = Mid(txtinput.Text, 1, 5)
txtinput.Select(txtinput.Text.Length, 0)
End If
'counters for letters and numbers
Dim letters As Integer = 0
Dim numbers As Integer = 0
'Parse and compare the input
For Each c As Char In txtinput.Text
If Asc(c) >= 48 And Asc(c) <= 57 Then 'ASCII characters for 0-9
numbers += 1
ElseIf Asc(c) >= 65 And Asc(c) <= 90 Then 'ASCII characters for A-Z
letters += 1
ElseIf Asc(c) >= 97 And Asc(c) <= 122 Then 'ASCII characters for a-z
letters += 1
End If
Next
If letters = 2 And numbers = 3 Then
lblMessage.Text = "Correct Format"
Else
lblMessage.Text = "Incorrect Format"
End If
使用 Linq:
If txtinput.Text.Length > 5 Then
txtinput.Text = Mid(txtinput.Text, 1, 5)
txtinput.Select(txtinput.Text.Length, 0)
End If
If txtinput.Text.Count(Function(x As Char) Char.IsLetter(x)) = 3 And txtinput.Text.Count(Function(x As Char) Char.IsNumber(x)) = 2 Then
lblMessage.Text = "Correct Format"
Else
lblMessage.Text = "Incorrect Format"
End If