FIltering what characters can be added to a text b

2019-02-20 18:15发布

问题:

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 symbols or numbers.

Now, he wants it so when you try and put in a special character it simply will not get entered into the text box. I know the logistics to this, but I'm not sure how I would go about coding it.

Basically what needs to happen is when the user types in characters like $, ^, 5, * etc, a function needs to recognise this and stop them from being entered into the textbox, whether it means deleting them as soon as they go in or interrupting the action altogether.

Anybody have some insight into this? Anything is appreciated, thanks.

回答1:

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.