Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Feb 24, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Test for Illegal Characters

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 Long
Public Function IsAlphaNum(ByVal sString As String) As Boolean
	Dim lPos As Long
	Const ALPHA_NUM As String = "abcdefgihjklmnopqrstuvwxyz" & _
	' 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.
Geir Arnesen
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date