Validating email address format on your ASP webpage

By alschneider at January 24, 2010 13:42
Filed Under: Web / Software Development, Marketing

If you’ve been a web developer for more than 5 minutes you know that you can’t create any type of website without getting a user to enter their email address. Sometimes this is done for marketing purposes or to add them to an email list for subscriptions, but whatever the reason the need is there on almost any website to prompt, validate, and record a visitors email address.

 

An easy way to do this is with a JavaScript chunk of code that will look at the value the user entered and ensure it adheres to certain rules regarding how a standard email address is formatted. This will not validate that the email is a working account at the domain specified (that’s another post), but it will at least catch user input errors they might not be aware of when entering the address in the field.

 

Test the code out on our email Format Test Page!

 

Download the ASP and Javascript code used on the test page here: emailFormatExample.zip (2.48 kb)

 

This file, emailTools.js, contains several functions that take a passed parameter and check the syntax to ensure it is formatted properly.

   1: function checkValidation(emailAddr) {
   2:     var message = 'OK';
   3:     if (stringEmpty(emailAddr)) {
   4:         message = "Error! There is no input value entered.";
   5:     } else if (noAtSign( emailAddr )) {
   6:         message = "Error! The address \"" + emailAddr + "\" does not contain an '@' character.";
   7:     } else if (nothingBeforeAt(emailAddr)) {
   8:         message = "Error! The address \"" + emailAddre;
   9:         message += "\" must contain at least one character before the '@' character";
  10:     } else if (noLeftBracket(emailAddr)) {
  11:         message = "Error! The address \"" + emailAddr;
  12:         message += "\" contains a right square bracket ']',\nbut no corresponding left square bracket '['.";
  13:     } else if (noRightBracket(emailAddr)) {
  14:         message = "Error! The address \"" + emailAddr;
  15:         message += "\" contains a left square bracket '[',\nbut no corresponding right square bracket ']'.";
  16:     } else if (noValidPeriod(emailAddr)) {
  17:         message = "Error! The address \"" + emailAddr + "\" must contain a period ('.') character.";
  18:     } else if (noValidSuffix(emailAddr)) {
  19:         message = "Error! The address \"" + emailAddr;
  20:         message += "\" must contain a two, three or four character suffix.";
  21:     }
  22:     return (message);
  23: }
  24:  
  25: function checkEmailValid (formField) {
  26:     if( checkValidation(formField) == 'OK')
  27:         return true;
  28:     return false;
  29: }
  30:  
  31: function stringEmpty (formField) {
  32:     // CHECK THAT THE STRING IS NOT EMPTY
  33:     if ( formField.length < 1 ) {
  34:         return ( true );
  35:     } else {
  36:         return ( false );
  37:     }
  38: }
  39:  
  40: function noAtSign (formField) {
  41:     // CHECK THAT THERE IS AN '@' CHARACTER IN THE STRING
  42:     if (formField.indexOf ('@', 0) == -1) {
  43:         return ( true )
  44:     } else {
  45:         return ( false );
  46:     }
  47: }
  48:  
  49: function nothingBeforeAt (formField) {
  50:     // CHECK THERE IS AT LEAST ONE CHARACTER BEFORE THE '@' CHARACTER
  51:     if ( formField.indexOf ( '@', 0 ) < 1 ) {
  52:         return ( true )
  53:     } else {
  54:         return ( false );
  55:     }
  56: }
  57:  
  58: function noLeftBracket (formField) {
  59:     // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR LEFT BRACKET
  60:     if ( formField.indexOf ( '[', 0 ) == -1 && formField.charAt (formField.length - 1) == ']') {
  61:         return ( true )
  62:     } else {
  63:         return ( false );
  64:     }
  65: }
  66:  
  67: function noRightBracket (formField) {
  68:     // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR RIGHT BRACKET
  69:     if (formField.indexOf ( '[', 0 ) > -1 && formField.charAt (formField.length - 1) != ']') {
  70:         return ( true );
  71:     } else {
  72:         return ( false );
  73:     }
  74: }
  75:  
  76: function noValidPeriod (formField) {
  77:     // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
  78:     if (formField.indexOf ( '@', 0 ) > 1 && formField.charAt (formField.length - 1 ) == ']')
  79:         return ( false );
  80:  
  81:     // CHECK THAT THERE IS AT LEAST ONE PERIOD IN THE STRING
  82:     if (formField.indexOf ( '.', 0 ) == -1)
  83:         return ( true );
  84:  
  85:     return ( false );
  86: }
  87:  
  88: function noValidSuffix(formField) {
  89:     // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
  90:     if (formField.indexOf('@', 0) > 1 && formField.charAt(formField.length - 1) == ']') {
  91:         return ( false );
  92:     }
  93:  
  94:     // CHECK THAT THERE IS A TWO OR THREE CHARACTER SUFFIX AFTER THE LAST PERIOD
  95:     var len = formField.length;
  96:     var pos = formField.lastIndexOf ( '.', len - 1 ) + 1;
  97:     if ( ( len - pos ) < 2 || ( len - pos ) > 4 ) {
  98:         return ( true );
  99:     } else {
 100:         return ( false );
 101:     }
 102: }

Create a file called emailTools.js ( or download the sample .ZIP file above ) and place it in your sites root directory.

 

In your .ASPX file, include a reference to the script file by adding the following line of code, preferably toward the bottom with other parts of your scripts.

   1: <script type="text/javascript" src="emailTools.js"></script>

Next, add the textbox control to your page that will hold the email address the user enters

   1: <asp:TextBox ID="emailaddr" runat="server" MaxLength="50" Style="vertical-align: middle"
   2:     TabIndex="1" Width="300px" CausesValidation="True"></asp:TextBox>

After the textbox control code that will contain the email address the visitor enters, you need to add a custom validator. Place it on the form so that if the user enters an address that is invalid, the message shows up on top of or below the email address textbox. This way the user can easily see the text when it pops up and make the necessary corrections. The first validator simply reminds the user that they need to enter an email address in order to continue. The second custom validator is what checks to see if the address is formatted correctly.

   1: <asp:RequiredFieldValidator ID="rfvFullname" runat="server" ControlToValidate="emailaddr"
   2:     ErrorMessage="Please enter your email address" Font-Bold="True" Font-Size="12pt" />
   3: <asp:CustomValidator ID="cvEmail" runat="server" Font-Bold="True" Font-Size="12pt"
   4:     ClientValidationFunction="checkEmailAddr" ControlToValidate="emailaddr" ErrorMessage="Email address is not formatted properly. Please correct." />

Change the ControlToValidate value to the name of your email address textbox control on the form.

 

Place a button on your form for the user to press when they are done.

   1: <asp:Button ID="Button1" runat="server" Text="Click to continue" OnClick="OnAddEmail" />

Notice how the button has an OnClick variable that tells it to run our C# code block called OnAddEmail() and not our validation script? That's because the control will never fire the OnClick event until the validation specified in the CustomValidator and RequiredFieldValidator occurs and everything checks out. In our code behind, we have two functions. One to take care of the PageLoad and set our previous page variable, the second is the actual OnAddEmail function that records the users email and returns them to the page that sent them here. I have placed the code within the ASPX file and not in a separate file, but you can do it either way.

   1: <script runat="server">
   2:     public static string sPrevPage = "";
   3:     protected void Page_Load(object sender, EventArgs e)
   4:     {
   5:         // Save the originating page so we can send the user back whe done
   6:         if (!IsPostBack)
   7:         {
   8:             if (Request.ServerVariables["HTTP_referer"] != null)
   9:                 sPrevPage = Request.ServerVariables["HTTP_referer"].ToString();
  10:             else
  11:                 sPrevPage = "~/Default.aspx";
  12:         }
  13:     }
  14:  
  15:     protected void OnAddEmail(object sender, EventArgs e)
  16:     {
  17:         // Use this function to write the email address to a file
  18:         try
  19:         {
  20:             string sFilePath = Request.MapPath("~/emails/") + "visitor.log";
  21:             using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sFilePath, true))
  22:             {
  23:                 sw.WriteLine(emailaddr.Text);
  24:             }
  25:         }
  26:         catch { }
  27:         Response.Redirect(sPrevPage);
  28:     }
  29: </script>

Now comes the fun part… Insert the code at the bottom of the ASPX file to call the function(s) in our emailtools.js file that will tell us whether or not the email address is at least formatted OK.

   1: <script language="javascript" type="text/javascript">
   2:     var alreadyChecked = false;
   3:     function checkEmailAddr(sender, args) {
   4:         var retVal = checkEmailValid(document.getElementById('<%=emailaddr.ClientID%>').value);
   5:         if (retVal == true && alreadyChecked == false) {
   6:             alert("Your address appears valid. You will now be taken back to the previous page...");
   7:             alreadyChecked = true;
   8:         }
   9:         args.IsValid = retVal;
  10:     }
  11: </script>

Now, when the user presses Enter or the submit button, the validation scripts fire. If they fail, they warn the user and lets them fix the errors on the form. Once a valid email is supplied, the name is recorded in the Visitors.log file, and they are returned to the previous screen or you can change the code to take them to a “Thank you” type page.

 

You may be wondering about the variable alreadyChecked. It is needed because the checkEmailAddr function actually fires twice when the user enters a valid email address… Once for the validation and again for the form submission. This variable ensures our textbox message only gets displayed once.

 

I hope this example helps and / or makes sense enough to help you with validating some of the user input.

Comments

1/23/2010 8:07:25 AM #

trackback

Validating email address format on your ASP webpage

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com | Reply

2/1/2010 3:22:34 AM #

craftsman sears

Thank nice post

craftsman sears United States | Reply

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading




Looking for more stories? Check out
Shoutwire Shoutwire - Internet News for the Masses

Help us out by visiting our sponsors!
Thank you

Protect Your Business


Recent Posts

Recent Comments

Comment RSS

What We're Playing




Who's Watchin' Me?