Friday, January 25, 2013

Sitecore field value validation: unique value

Someone asked me today if Sitecore can validate whether an item's siblings contained unique values for a specific field. This post will describe how to create a custom field validator that will do just that.

1. Create the custom field validation rule in Sitecore
2. Create a class in a class library project for your code. The class should inherit from Sitecore.Data.Validators.StandardValidator

custom field validation rule

3. The example here has a custom parameter defined for 'parent' item path, which would specify the sub-tree of items against which field values are validated. The query selects all items that have the same field and value for that field as the currently validated one. Starting at the 'parent'.


public class UniqueValueValidator : StandardValidator
    {
      protected override ValidatorResult Evaluate()
        {
            string parent = this.Parameters["parent"];
            string value = base.GetControlValidationValue();
            string query = string.Format("{0}//*[@{1} = '{2}']", parent, this.GetFieldDisplayName(), value);

            foreach (Item item in global::Sitecore.Data.Database.GetDatabase("master").SelectItems(query))
            {
                //skip the current item
                if (item.ID != base.GetField().Item.ID)
                {
                    //set the error message
                    Text = GetText("Value must be unique. Item \"{0}\" contains the same value in field \"{1}\".", new[]{ item.DisplayName, GetFieldDisplayName()});
                    
                    return ValidatorResult.Error;
                }
            }

            return ValidatorResult.Valid;
        }

        protected override ValidatorResult GetMaxValidatorResult()
        {
            return GetFailedResult(ValidatorResult.Warning);
        }

        public override string Name
        {
            get
            {
                return "UniqueValue";
            }
        }
}

It is important to note that having a custom validator in place will not prevent an editor from creating items with duplicate field values. All it will do is provide feedback, so the solution should still be able to handle duplicate field values if they do appear.