Skip to main content
2 of 3
Clarify the type of validation
Dan Sinclair
  • 5.5k
  • 2
  • 20
  • 44

I would recommend implementing a custom Item validation rule.

Note: This is different from a field validation, in that it validates the entire item instead of a single field.

1. Create custom validator

Create a new class that implements the Sitecore.Data.Validators.StandardValidator base class. In the Evaluate() method, get both fields and check to see if either of them has a value:

public class AtLeastOneFieldPopulatedValidator : StandardValidator
{
    public override string Name => "At Least One Field Populated";

    public AtLeastOneFieldPopulatedValidator() {}

    public UrlCharacterValidator(SerializationInfo info, StreamingContext context) : base(info, context) {}

    protected override ValidatorResult Evaluate()
    {
        Item item = base.GetItem();
        if (item == null)
        {
            return ValidatorResult.Valid;
        }
        if (!string.IsNullOrEmpty(item["Field 1"]) || !string.IsNullOrEmpty(item["Field 2"]))
        {
            return ValidatorResult.Valid;
        }
        return base.GetFailedResult(ValidatorResult.CriticalError);
    }

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

2. Create Validation Rule item

First, create a new Validation Rule (template /sitecore/templates/System/Validation/Validation Rule) item somewhere below this node:

/sitecore/system/Settings/Validation Rules/Item Rules

item validator tree

Important: Make sure you populate the Type field with your fully-qualified name of your custom validator's class (e.g. Custom.Services.AtLeastOneFieldPopulatedValidator, Custom.Services).

3. Associate your Validation Rule to your items

On the __Standard values of your item's template, show Standard Fields (View ribbon tab -> Standard fields) and add your Validation Rule to the appropriate validation fields. I recommend including it in all four.

(Optional) Extra credit: Add parameters

I've not tested this, but I'm sure there's a way to pass parameters using the Parameters field on the Validation Rule item. In these parameters, you could pass a list of the fields to check so your validator can be reused by creating multiple Validation Rule items in Sitecore.

parameters field

Dan Sinclair
  • 5.5k
  • 2
  • 20
  • 44