Skip to main content

Thinking out aloud - Dave Hunter's SharePoint Blog

Go Search
Home
Blog
  

Locations of visitors to this page


 Useful Links

  Microsoft UK events
  SharePoint 2007 on CodePlex
  SharePoint Community Portal
  SharePoint User Group
  SharePoint Community Portal
  SharePoint Pedia
  SharePoint MSDN Forums
  SharePoint University
Home > Thinking out aloud - Dave Hunter's SharePoint Blog > Posts > SharePoint Event Receivers By Example - Email Validation
My thoughts and findings on Microsoft Information worker technologies, including MCMS and SharePoint 2007 (MOSS).
SharePoint Event Receivers By Example - Email Validation

A while ago I wrote the article Delving into SharePoint 2007 Event Receivers its a popular article but lacks something, which I believe are some real world examples people can see in action and relate to ... Introducing the next series of articles SharePoint Event Receivers By Example.

One of the out of the box libraries in SharePoint is the contact list.  This holds contact information such as First Name, Last Name, Telephone, Email etc.  The email column is a standard single line of text site column.  I wanted to validate the email address users whilst creating contacts. 

Event Receivers have before or after events.  You would use a before event to capture users creating contacts and updating contacts.  You need to use the SPItemEventReceiver class and utilise the ItemAdding and ItemUpdating events.

To check the values that the user enters during a before event you should check the properties.AfterProperties.  This is a collection of name value pairs.  You can retrieve a value using the internal name of a column (not the display name).  For example:

string emailMessage = properties.AfterProperties["Email"].ToString();

You can cancel the event using:

properties.Status = SPEventReceiverStatus.CancelWithError;
properties.Cancel = true;
properties.ErrorMessage = "Please enter a valid email address";

 

The Status is set to cancel and display an error.  properties.Cancel determines if the event should be cancelled.  The default is false but once you set it to true it will cancel the event when the current execution ends.  An error message is set using the ErrorMessage property.  The following is displayed to the user:

 Email Validation using Event Receivers

Here's the code:

#region namespaces
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

using Microsoft.SharePoint;
using System.Collections;
#endregion

namespace Dhunter.SharePoint.EventReceivers
{
    public class ValidEmailEventReceiver : SPItemEventReceiver
    {
        #region events

        /// <summary>
        /// Test the email expression when the user creates a new item
        /// </summary>
        /// <param name="properties"></param>
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);

            // only perform if we have an Email column
            if (properties.AfterProperties["Email"] != null)
            {
                // test to see if the email is valid
                if (!IsValidEmailAddress(properties.AfterProperties["Email"].ToString()))
                {
                    // email validation failed, so display an error
                    properties.Status = SPEventReceiverStatus.CancelWithError;
                    properties.Cancel = true;
                    properties.ErrorMessage = "Please enter a valid email address";
                    
                }
            }

            
        }

        /// <summary>
        /// Test the email expression when the user updates an existing item
        /// </summary>
        /// <param name="properties"></param>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);

            // only perform if we have an Email column
            if (properties.AfterProperties["Email"] != null)
            {
                // test to see if the email is valid
                if (!IsValidEmailAddress(properties.AfterProperties["Email"].ToString()))
                {
                    // email validation failed, so display an error
                    properties.Status = SPEventReceiverStatus.CancelWithError;
                    properties.Cancel = true;
                    properties.ErrorMessage = "Please enter a valid email address";
                    
                }
            }

            
        }

        #endregion

        #region private methods

        /// <summary>
        /// Test the email address to see if it meets the validation
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        private bool IsValidEmailAddress(string email)
        {
            bool isValid = false;

            // regular expression to test the email
            string emailRegEx = @"^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|
(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$"; // run the test Regex reStrict = new Regex(emailRegEx); isValid = reStrict.IsMatch(email); // flag to indicate if its valid return isValid; } #endregion } }

 

My findings during creating this event receiver

  • BeforeProperties are only available in Event Receivers bound to a document library.  For more information please see http://msdn.microsoft.com/en-us/library/aa979520.aspx
  • BeforeProperties and AfterProperties contain a collection of DictionaryEntry's you should use the internal name of the column.  I tried this using the email address.  The internal name can be found by editing a site column and looking in the url, for example: /_layouts/fldedit.aspx?field=EMail.  I tried using properties.AfterProperties["EMail"] always returned null.  After looking into the collection the field was actually called "Email".  You can check these names using:

foreach (DictionaryEntry de in properties.AfterProperties)
{
  string key = de.Key.ToString();
  string value = de.Value.ToString();
}

  • Cancel doesn't stop the ItemAdding or ItemUpdating unless base.ItemAdding(properties); is called at the top of the event.
  • I used the SharePoint Tips Utility Pack http://www.codeplex.com/spstipsUtilityPack to bind the event receiver to the list.  The tool has a event handler management section that allows you to quickly register your event receiver to a list.

Happy coding.

  Copyright
This work is licenced under a Creative Commons Attribution-Noncommercial-No Derivative Works 2.0 UK: England & Wales License
  Site Map

Comments

Good Article Dave

Keep the good work goin....
at 06/07/2009 12:34

Do you find this hard to use?

I've encountered the same event handler experience and it doesn't really work for me. From the user's perspective, I don't like getting the error message on a new page that requires me to use the back button. How do you feel about that?
at 10/08/2009 22:25

Good article

very good
at 23/09/2009 20:05

 Dave Hunter

I'm currently a Senior Consultant at Netstore 2e2. I specialise in Microsoft Information Worker technologies (especially MOSS, MCMS and .NET), with over 8 years of experience within this area of specialism. 

I have gained two certifications for MOSS and WSS and look to complete the full certification track soon.

View Dave Hunter's profile on LinkedIn

  Subscribe in a reader


 Latest Posts

I’m attending the first ever SharePoint Saturday in the UK31/08/2010 19:43
I’ve re-joined CIBER UK31/08/2010 19:26
I’ve been Awarded a MVP for SharePoint01/04/2010 19:49
SharePoint 2010 Training on Microsoft E-Learning15/03/2010 17:56
SharePoint UK User Group - Thursday 27th August London Meeting25/08/2009 17:56
CAML Query that filters on the current user23/07/2009 17:50
Microsoft Ramp Up Free SharePoint Developer Training22/07/2009 20:59
How To: Change a SharePoint Application Pool Programmatically07/07/2009 18:08
SharePoint Forums Topping 100 Answers06/07/2009 12:29
Find out the SharePoint Internal Name for a Column or Site Column28/05/2009 09:56
1 - 10 Next