I’ve just put together this regExp function that checks the contents of a string. The string should only contain numbers, letters, fullstops (.), hyphens (-), at signs (@) and apostrophes (‘).
If Trim(Request("searchStr")) <> "" Then
Function validateSearchStr(searchStr)
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Pattern = "[\w'-@.]"
validateSearchStr = regEx.Test(searchStr)
End Function
If NOT validateSearchStr(Trim(Request("searchStr"))) Then
Response.Redirect("error/?e=badInput")
End If
End If
But this doesn’t seem to be doing anything, at all. I can type all characters and symbols and the error page does not fire.
Is it obvious?
First off, if you want to match a literal hyphen in the character class, you need to escape (ie backslash) it:
regEx.Pattern = "[\w'\-@.]".Second, note
\wallows underscores as well — if you didn’t want that useA-Za-z0-9.Second off, it looks like
validateSearchStrjust tests if there is any character in your string that matches your regex.So the searchstring ‘abcasdf#ljasdf’ is invalid, but since it matches
[A-Za-z0-9'\-@.](for example the first “a” matches), no error is thrown.I think you should instead test if there are any illegal characters. i.e.:
Note the
^in the character class which says “any character but these”.Now the
regEx.Testwill return TRUE if there is a bad character in the search string.So rename
validateSearchStrtoisSearchStrBadand do:(Note, if you want to test whether the entire string is valid your regex would have to be
"^[A-Za-z0-9'\-@.]+$]", i.e. make sure every character of the string matches, not just one character).