Sitecore's RuleValidator for validating multiple fields at once

Problem statement

We want to make sure that someone enters a value in one of two fields: "Field 1" or "Field 2." It does not matter which, and the user does not need to enter a value in both.

Can we fix it with a field validator?

Usually, when we need to validate an item conforms to some set of rules, we apply Field Validators:The problem with field validators, however, is that they only understand a single field and do not have access to the rest of the item being validated. If you need more than a single field (for example to validate two fields against each other), you need access to the entire item. This is where the less commonly-used Item Validator comes in.

Hmm, what's an item validator?

Item validators work a little differently:

  • Instead of validating a single field, item validators interact with the entire item
  • They can't show an error or warning color next to fields (because they're not tied to fields), but they still show up as an error or warning on the right side of the content editor or in any validation tools (Review tab -> Validation, Validate workflow step, gutter icon, etc.)

A number of out-of-the-box item validators exist already:

So how do I solve it?

Just like with field validators, you can make a custom item validator by overriding the Sitecore.Data.Validators.StandardValidator class and implementing the Evaluate() method.In our case, however, this isn't necessary. There is already code in Sitecore.Kernel that does what we need: the Sitecore.Data.Validators.ItemValidators.RuleValidator.To do it:

  1. Somewhere under the /sitecore/system/Settings/Validation Rules/Item Rules node, insert an item from template Rules Validation Rule (/sitecore/templates/System/Validation/Rules Validation Rule)
  2. Set the Type field to Sitecore.Data.Validators.ItemValidators.RuleValidator,Sitecore.Kernel
  3. In the Rule field, add two conditions and an action as indicated below:
    1. where the "Field 1" field is empty
    2. and where the "Field 2" field is empty
    3. Set CriticalError validation result, Both the "Field 1" and "Field 2" fields are empty
  4. Customize the Title and Description fields as desired so they show the user what you want them to see when validating this item
  5. Select the __Standard Values of the template to which you want to apply this validation
  6. In the Validation Rules section, add this template to all four fields:
    1. Quick action bar validation rules
    2. Validation button validation rules
    3. Validation bar validation rules
    4. Workflow validation rules