PSBailey.co.uk - homepage

Email Address Validation (ASP)


Note: This article is also available as a PHP article.

It’s something that every site maker will have to worry about at some point or other — how to capture accurate email addresses. Luckily, with a scripting language like PHP or ASP it becomes much easier. So, without further ado, here is a function to validate email addresses in ASP. Instructions for how to call it are below.

NOTE: » indicates a line break.

<%
'check if an email follows the format: a@aa.aa
'returns true or false.
function validemail(address)
 Dim objRegExpr
 Dim matcharray
 Set objRegExpr = New regexp
 objRegExpr.Pattern = "^[\w~'\-\.]+@[\w\-\.]{2,}\.[a-zA-Z\d]{2,4}$"
 Set matcharray = objRegExpr.Execute(email)
 if (matcharray.count > 0) then
   validemail = True
 else
   validemail = False
 end if
end function
%>

How It Works

Regular expressions are handy little blighters. They are very good at spotting patterns in strings of text, and this is exactly what they have done here. It will look for [at least one alphanumeric character, single quote, tilda, dash or full stop] followed by [an @ symbol] followed by [ at least 2 alphanumeric characters, dash or full stop] followed by [a full stop] followed by [between 2 and 4 alpanumeric characters]. This is by no means bullet proof, a user could still enter 11@11.11 for instance, and that would be perfectly valid. This should not be your only line of defence against bogus email addresses, but it’s a good start.

In case you're thinking you’ll never get a user with a single quote in their email name, wait till you get john_o'reilly@aol.com. AOL is one of a few ISPs who have bucked the trend and allowed them through. It’s a good idea to fix these addresses before you go adding them to your database too, as the single quote could break your carefully constructed SQL statements. You have been warned.

Note: Regular expressions should only be used when there is a significant gain over ASP’s traditional string manipulation functions. They are generally are not as fast as a line or two of standard stuff, but in this case the saving will be 10-15 lines of code so it is as quick as standard methods.

How To Call It

This function will only need to be defined once for any page of ASP, or better still put into an include file for use throughout the website. It is called like so:

<%
email_from_user = "foo@madeupaddress";

if (validemail(email_from_user))then
  Response.write("Thanks for a valid email address.")
else
  Response.write("That aint no valid address punk!!!")
end if
%>

You can download a fully working example to play with at your leisure. Just place the enclosed files on an ASP enabled environment and you’re away. This article is also available as a PHP article.

Feel free to use this code any way you like, however, a link to my site (this page or any other) would be very much appreciated in return. Thanks.

Get Firefox! Valid XHTML Valid CSS