A Note About Custom Validators for MVC with Sitecore

Sitecore

Sitecore

In a post about creating editable labels in Sitecore from John West, he points out a technique to allow a developer to use annotations within your MVC model to attach “fields” within the context item that would be used to label form fields.

The same technique can be used to power custom validators with editable error messages.

First, create the class for the attribute:

public class SitecoreRequiredAttribute : RequiredAttribute
{
   // the name of a field within the current item that contains the error message
   public string ErrorMessageFieldName { get; set; }

   // for rendering field values
   private Sitecore.Mvc.Helpers.SitecoreHelper _sitecoreHelper;

   private ID ItemID { get; set; }

   public SitecoreRequiredAttribute(string errorMessageFieldName)
   {
      ErrorMessageFieldName = errorMessageFieldName;
      ItemID = SitecoreHelper.CurrentItem.ID;
   }

   public SitecoreRequiredAttribute()
   {
      ItemID = SitecoreHelper.CurrentItem.ID;
   }

   public override string FormatErrorMessage(string name)
   {
      if (String.IsNullOrEmpty(ErrorMessageFieldName))
      {
         return base.FormatErrorMessage(name);
      }

      Database database = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database;
      Item item = database.GetItem(ItemID);

      return SitecoreHelper.Field(ErrorMessageFieldName, item).ToString();

   }

   // lazy load sitecoreHelper
   private Sitecore.Mvc.Helpers.SitecoreHelper SitecoreHelper
   {
      get { return _sitecoreHelper ?? (_sitecoreHelper = SitecoreHelperHelper.GetSitecoreHelper()); }
   }

}

(note – the SitecoreHelperHelper refers to John’s code that will fetch the Html Helper item).

Brian Beckham

I am the President and CEO of BrainJocks. As a Sitecore MVP, I spend most of my time consulting and architecting software solutions for enterprise-level Sitecore projects.

More posts from Brian >

Add a Comment

Your email address will not be published. Required fields are marked *

Or request call back