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:
- 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)
- Set the Type field to Sitecore.Data.Validators.ItemValidators.RuleValidator,Sitecore.Kernel
- In the Rule field, add two conditions and an action as indicated below:
- Customize the Title and Description fields as desired so they show the user what you want them to see when validating this item
- Select the __Standard Values of the template to which you want to apply this validation
- In the Validation Rules section, add this template to all four fields:
- Quick action bar validation rules
- Validation button validation rules
- Validation bar validation rules
- Workflow validation rules