Use this fast function to test for the occurrence of nonalphanumeric characters in a string:
Private Declare Function StrSpn Lib "SHLWAPI" Alias _ "StrSpnW" (ByVal psz As Long, ByVal pszSet As Long) As LongPublic Function IsAlphaNum(ByVal sString As String) As Boolean Dim lPos As Long Const ALPHA_NUM As String = "abcdefgihjklmnopqrstuvwxyz" & _ "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" ' Returns the first occurrence of nonmatching characters lPos = StrSpn(StrPtr(pString), StrPtr(pAlphaNum)) ' If the return position is not equal to the length of the ' input string, nonalphanumeric chars were found. IsAlphaNum = (lPos = Len(sString))End Function
You can easily modify this function to scan for invalid characters by editing the ALPHA_NUM constant so it includes only characters you consider legal.
Editor’s Note: The StrSpn function relies on the version of shlwapi.dll that ships with Internet Explorer 4.0 and later. Handle errors?and expectations?accordingly.