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
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.