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