FIltering what characters can be added to a text box

后端 未结 1 1181
臣服心动
臣服心动 2021-01-16 09:00

I have a series of text boxes on my form, and my client wants me to filter out characters that aren\'t allowed, for example in the name field you cannot have sy

相关标签:
1条回答
  • 2021-01-16 09:36

    You could use a regex:

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        StripNonAlphabetCharacters(TextBox1)
    End Sub
    
    Public Sub StripNonAlphabetCharacters(ByVal input As TextBox)
        ' pattern matches any character that is NOT A-Z (allows upper and lower case alphabets)
        Dim rx As New Regex("[^a-zA-Z]")
        If (rx.IsMatch(input.Text)) Then
            Dim startPosition As Integer = input.SelectionStart - 1
            input.Text = rx.Replace(input.Text, "")
            input.SelectionStart = startPosition
        End If
    End Sub
    

    The actual Regex ought to be made a member of the form so it isn't declared each time or placed into some common class for reference. The selection logic is used to keep the cursor at its current location after stripping the invalid characters.


    For WinForms you can use the MaskedTextBox Class and set the Mask property.

    For ASP.NET you could use the AJAX Toolkit's MaskedEdit control.

    0 讨论(0)
提交回复
热议问题