“Code-easy” modifications for SharePoint 2010: Part 1, the Validating Email Field

I always wanted to do a series about easy to build, real life customer requests for SharePoint modifications. And as with most ideas, never really found the time to do it. Well, now’s as good a time as any!

Other parts:

So here is part 1, the Validating Email Field.

SharePoint 2010 Foundation finally enables field validation through formulas which is great. But this may not be the best solution if you want to apply custom (or more complex) validation rules. One common customer request heard often is to validate email address inputs. And for this simple request I personally like to use Regular Expressions instead of calculated formulas. I have seen a couple of nice solutions using a more generic Regular Expression Custom Field, but in my case I would like to keep it clean and simple and hide the complexity of the Regular Expression itself.

Something like this, a standard text input field that throws an error if you input an invalid email address:

4

And have the error message configurable, because we want to support different scenarios:

3

Couple of things we need for our custom field:

  1. A class for our Validating Email Field. Since email addresses tend to consist of text characters only, we start by inheriting from the SPTextField class.
  2. A class for our custom validation, based on the PresentationFramework ValidationRule class. This way, we can reuse it in later projects.
  3. Deployment files, in this case we need a FLDTYPES_*.XML file defining our new field.

To start, create a Visual Studio 2010 Empty SharePoint solution. Since the assembly needs to go in the GAC (see my earlier post about Sandbox solutions), we select a farm solution.

1

Our class needs the following:

  • Since we want to configure our validation error message through the field’s properties, we need a property for this in our class.
  • An override for the GetValidatedString method where we can perform our email validation.

Create a class for our custom field; in this case we call it the ValidatingEmailField and add a property for the error message:

namespace Blog.Examples.ValidatingFields
{
    public class ValidatingEmailField : SPFieldText
    {
        private string _validatedErrorMessage;
        public string ValidatedErrorMessage
        {
            get
            {
                return _validatedErrorMessage;
            }
            set
            {
                _validatedErrorMessage = value;
            }
        }

        private void Init()
        {
            object validatedErrorMessageValue = GetCustomProperty("ValidatedErrorMessage");

            if (validatedErrorMessageValue != null)
            {
                ValidatedErrorMessage = validatedErrorMessageValue.ToString();
            }
        }

        public ValidatingEmailField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
            this.Init();
        }

  	 public ValidatingEmailField(SPFieldCollection fields, String typeName, String displayName)
            : base(fields, typeName, displayName)
        {
            this.Init();
        }
    }
}

Then we add our override method to this class. This method uses our custom EmailValidationRule class which we will create next.

public override string GetValidatedString(object value)
        {
            if (value == null)
            {
                return string.Empty;
            }
            else
            {
                // Use our custom EmailValidationRule class.
                // Because it is based on .Net's ValidationRule, we pass the current CultureInfo
                CultureInfo cultureInfo = SPContext.Current.Web.UICulture;
                EmailValidationRule emailValidationRule = new EmailValidationRule();
                ValidationResult emailValidationResult = emailValidationRule.Validate(value, cultureInfo);

                if (emailValidationResult.IsValid)
                {
                    return base.GetValidatedString(value);
                }
                else
                {
                    throw new SPFieldValidationException(ValidatedErrorMessage);
                }
            }
        }

Next: the EmailValidationRule class. There are a few ways you can validate an email address, but as said earlier I like to use a regular expression for this.

namespace Blog.Examples.ValidatingFields
{
    public class EmailValidationRule : ValidationRule
    {
        public EmailValidationRule()
        {
        }

        public override ValidationResult Validate(object value, CultureInfo culture)
        {
            // Only UpperCase matches, so make sure you set IgnoreCase
            const string EMAILREGEX = "^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\\.)+[A-Z]{2,4}$";

            if (value != null)
            {
                Regex regex = new Regex(EMAILREGEX, RegexOptions.IgnoreCase);

                if (regex.IsMatch(value.ToString()))
                {
                    return new ValidationResult(true, "Valid email address.");
                }
                else
                {
                    return new ValidationResult(false, "Invalid email address.");
                }
            }
            else
            {
                return new ValidationResult(false, "No value entered.");
            }
        }
    }
}

A small note on the expression used: this expression will match most common email addresses, but there are some exceptions that will not. For example, top level domain names with more than 4 characters will fail.

And finally the deployment file.

Add a SharePoint mapped folder to your project pointing to “{SharePointRoot}\Template\XML”

2

Add a new xml file to this mapped folder: Fldtypes_<your unique field name>.xml .

Important: Make sure the filename is unique, because every custom field you will ever add will end up in this folder.

<?xml version="1.0" encoding="utf-8" ?>


    ValidatingEmailField
    Text
    Email address
    TRUE
    TRUE
    TRUE
    TRUE
    Blog.Examples.ValidatingFields.ValidatingEmailField,
Blog.Examples.ValidatingFields,Version=1.0.0.0,Culture=neutral,
PublicKeyToken=fd1fbc97e8ceddac







That’s it, package and deploy!

You can download the Visual Studio 2010 solution here.

Part 2 will be about building and deploying your custom Content Query Web Part Item Style.

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s