Mike Trethowan

Pen Truth Contributor

I have viewed many methods for checking a string for specific characters on the Internets. While there are number of methods contained within .NET, none worked 100%. Regex wasn’t good enough for me, nor was GetInvalidFileNameChar() as each would miss some invalid characters.  I needed a sure, quick easy way to check if a string entered into a Textbox was valid for a file name.  Finally I had to devise a simple method that I could easily control.  For those needing ideas, here is my code.


    Public Function invalidChar(ByVal test As String) As Boolean
        invalidChar = False
        For Each c As Char In test
            Select Case c
                Case "~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "+", "=", "{", "}", _
                     "[", "]", ";", "/", "\", "|", ":", ";", "'", "<", ">", ",", ".", "?", Chr(34) ' Char(34) = "
                    invalidChar = True
            End Select
    End Function


This can be associated with a Button Click Event or within the TextChanged Event code of your Textbox.


    Private Sub txbFileName_TextChanged(sender As Object, e As EventArgs) Handles txbFileName.TextChanged

        If invalidChar(txbFileName.Text) Then txbFileName.Text = txbFileName.Text.Remove(txbFileName.TextLength - 1, 1) ' Deletes the invalid char
        txbFileName.Select(txbFileName.Text.Length, 0) ' Returns the cursor back to the end of the string in the Textbox

    End Sub


Comments are closed.