Skip to main content

Back-End Development

A Note About Custom Validators for MVC with Sitecore

Abstract 13
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).

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Brian Beckham

As a Sitecore MVP, Brian spends most of his time consulting and architecting software solutions for enterprise-level Sitecore projects.

More from this Author

Follow Us