I got a requirement that I need to create more data templates with the same fields but the fields should have different validations based on the template. So I decided to create a base template and inherit the other templates from this. Now, how can I assign different validators for the fields based on the template?
Found out give a try for Sitecore Rules Engine. By default it provides rules and validators which I exactly need. Let’s setup my rules!
Navigation Level 1 rule:
Navigation Level 3 rule:
The rules actually are, that the Link field is required for Navigation Level 1 and Navigation Level 3 but not for Navigation Level 2.
To activate the Validator Rules for my template, I need use the /sitecore/system/Settings/Validation Rules/Item Rules/Rules/Validation Rules item validator on the standard values on the base template.
So cool, I almost found what I need, the problem now that as it is an Item Rule it is calling the validation on item save.
I want to make it more user friendly. Run the validation and show the error message when the user changing that particular field value.
To make this I found out why I can’t use the same “Rule Runner” validation on the field validation? To do this I needed to copy the /sitecore/system/Settings/Validation Rules/Item Rules/Rules/Validation Rules item validator into the Field Rules root folder like on the following screenshot.
Let’s setup the Base Navigation Item template’s Link field to use the /sitecore/system/Settings/Validation Rules/Field Rules/Rules/Validation Rules validation.
Voilà! Sitecore calls the same method and executing the rules what I set up in the Validation Rules!
I thought that it is enough to reuse the /sitecore/system/Settings/Validation Rules/Item Rules/Rules/Validation Rule item from Sitecore, but it isn’t. The problem with that, it is only checking the saved item values and does not know anything about the field itself. So I had to implement some additional things.
At first I needed to implement my custom field validator which is validating on field level.
As you can see this implementation needs a FieldValidatorsRuleContext which is a really dump class and containing the following properties.
I needed to use this implementation in my new Field Validator.
Then use this Field Validator on the field of the template then it is running the rules under /sitecore/system/Settings/Rules/MyProject/Foundation/Validation/Field Validation Rules/Rules item.
Unfortunately I also needed to implement my own rule which is checking the length of the value. The implementation is the following.
The most important part and the main difference is that it is checking the Field ID. And only runs the validation if the Field ID is matching. In Sitecore it looks like the following.