An odd Sitecore field validator

Today I faced a Sitecore website rollout problem I’ve never thought of before. When doing a multi language/multi market solution, it’s common to use cloning or other kinds of fallback techniques. This is typically very good, but sometimes it brings some new problems as well.

The scenario I faced was that I wanted to make sure that certain fields did not inherit any value from standard values, default values or via cloning. In my particular case, I wanted to ensure that certain integration settings where defined for each website, even if the sites were cloned. Maybe not a very common requirement, but here’s another example:

Let’s say you have a field that stores a Google Analytics UA code, maybe that code should be defined on each locations where it’s used. Not inherited between sites. (Depending on how you’ve configured GA of course.)

A simple way of solving this is to create a Field Validator that tests this. Here’s some sample code on how to implement such validator:

public class FieldDoesNotInheritValueValidator : StandardValidator
{
	protected override ValidatorResult Evaluate()
	{
		var field = GetField();
		if (field == null)
			return ValidatorResult.Valid;

		// Get field value without resolving fallbacks
		if (field.GetValue(false, false) != null)
			return ValidatorResult.Valid;

		Text = GetText("The field \"{0}\" does not contain a value.", GetFieldDisplayName());
		return GetFailedResult(ValidatorResult.Warning);
	}

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

	public override string Name
	{
		get { return "Field does not inherit value"; }
	}
}

Just add a new Validation Rule item among the master:/sitecore/system/Settings/Validation Rules/Field Rules and define the class above Your.Namespace.FieldDoesNotInheritValueValidator, Your.Assembly as any other Field validation rule

2 thoughts on “An odd Sitecore field validator

Leave a Reply