验证字符串用户输入

时间:2013-03-27 00:58:20

标签: vb.net validation

我的问题是我试图让用户只能输入“a,b,c或d”。如果他们没有输入这四个字母中的一个而不是用户只能输入这些字母,我宁愿错误输出。我只能通过数字数据找到与此类似的资源(使用try catch)。任何网站或提示都会很棒。

                If String.Compare(TextBox2.Text, "a", True) = 0 AndAlso String.Compare(TextBox21.Text, "a", True) = 0 Then
                'MessageBox.Show("A")
                totCorrect = totCorrect + corAns
            ElseIf String.Compare(TextBox2.Text, "b", True) = 0 AndAlso String.Compare(TextBox21.Text, "b", True) = 0 Then
                'MessageBox.Show("B")
                totCorrect = totCorrect + corAns
            ElseIf String.Compare(TextBox2.Text, "c", True) = 0 AndAlso String.Compare(TextBox21.Text, "c", True) = 0 Then
                'MessageBox.Show("C")
                totCorrect = totCorrect + corAns
            ElseIf String.Compare(TextBox2.Text, "d", True) = 0 AndAlso String.Compare(TextBox21.Text, "d", True) = 0 Then
                'MessageBox.Show("D")
                totCorrect = totCorrect + corAns
            Else
                totWrong = totWrong + wrgAns
                Label13.Visible = True
            End If

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress

    Dim allowableChar As New List(Of Char) From {"a"c, "b"c, "c"c, "d"c}

    Call allowableChar.AddRange(allowableChar.Select(Function(c) Convert.ToChar(c.ToString().ToUpper())).ToList())

    If Not (allowableChar.Contains(e.KeyChar) OrElse e.KeyChar = Convert.ToChar(Keys.Delete) OrElse e.KeyChar = Convert.ToChar(Keys.Back)) Then
        e.Handled = True
    End If

End Sub

Call allowableChar.AddRange(...)也会将大写字符添加到列表中。就像现在一样,这会在每次执行方法时生成一个新列表,这有点浪费......如果你使用这段代码我会建议你允许的字符列表一个类级变量并只填充它一次在表单的构造函数中。

要仅允许每种类型的一次字符,请使用:

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress

    Dim allowableChar As New List(Of Char) From {"a"c, "b"c, "c"c, "d"c}

    Call allowableChar.AddRange(allowableChar.Select(Function(c) Convert.ToChar(c.ToString().ToUpper())).ToList())

    If Not (allowableChar.Contains(e.KeyChar) OrElse e.KeyChar = Convert.ToChar(Keys.Delete) OrElse e.KeyChar = Convert.ToChar(Keys.Back)) Then
        e.Handled = True
    Else
        If Me.TextBox1.Text.Count(Function(c) c = e.KeyChar) >= 1 Then
            e.Handled = True
        End If
    End If

End Sub