By Ian Stallings
| Updated Regular Expression |
|---|
| Ian has an updated version of this function at ASPFAQs.com. |
Validating user input is a basic but very necessary part of web
development, especially when dealing with databases. Queries don't
go too well when you have !@)#$*%?= in the search field. So we
have to build a function that searches the input string for illegal
characters (defined by you) and then let the user know.
If you've used Asp's before you probably know that you can use the following vbscript to validate input:
<%
If (InStr(request.form("password"),"!") > 0) Then
response.write "Username cannot contain odd characters"
End If
%>
But what about multiple characters? We could use the above vbscript but it's not very efficient when dealing with multiple characters. I like to use Javacript as the language of choice because of it's ability to use regular expressions.
So what are regular expressions? Regular expressions are used in pattern matching and substitution. The regular expression interpreter takes your grammar, compares it with the string you're doing pattern matching on, then returns a true or false. True meaning it found a match, false meaning it didn't.
So, now that we've covered the basics let's dig into the code. The following javascript function will validate the string:
<script language=javascript runat=server>
function inStrGrp(src,reg) {
var regex=new RegExp("[" + reg + "]","i");
return regex.test(src);
}
</script>
You would then call this from your vbscript code using the following:
<%
If inStrGrp(request.form("password"),"!,@#%$^&*()+=") = True Then
response.write "Password cannot contain odd characters"
end if
%>
And that is it. Not 100 lines of code, just 10. You can add characters to the expression if you need to. If you have any comments or questions feel free to email me at madcow@olg.com!
Ian Stallings is a 26 year old Software Engineer from the Washington DC area. He has experience in Internet/Intranet development using ASP, VB, Java, SQL Server, and IIS. Prior to devoting his career to application development he worked as a systems administrator at a small ISP.
When not developing applications or tinkering with computers, he masquerades as a normal human being




