views:

136

answers:

1

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.

A: 

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.

Ahmad Mageed
Hi, thanks for the answer. While that solution would work this is actually for a college project (the client is my college) and they want to see some sort of function to handle this, not for it to all get handled with a pre-made control. But thanks for the contribution, it'll come in handy for me :)
Matt
@Matt I've updated my response for a WinForms scenario. You could write a similar function that accepts a string instead of a textbox control and return the stripped result if needed.
Ahmad Mageed