Hello learners, Welcome to Learn Sitecore.
In this blog we will see how to create custom field validation rule for a field of an item. Providing a field validation rule to a field provides a great flexibility to the developers as well as good experience for content authors. By adding it choosing an invalid date by content author and showing it in the website can be eliminated at the first step itself. It is recommended to use field validations for different fields based on the business requirements.
To implement a custom field rule validation, navigate to /sitecore/system/Settings/Validation Rules/Field Rules and insert a validation rule. After that fill the data into Text and Data sections as follows.
| Text Section |
| Data Section |
In the Type field add the data as class reference name, assembly name.
Now create a class file that extends the standard validator class. Write the logic as per your requirement in the Evaluate function. For the instance I have added a sample code which validates the end date of an item using the start date field information as shown below. Here the assumption is the item contains Start Date and End Date fields in it.
Here base.GetItem() function will return the editing item from Sitecore. ControlValidationValue will return the raw value of field for which the rule is applied.
Now switch to Sitecore and navigate to the field to apply this validation rule. In the validation rules section of field choose as shown.
| Apply Validation rule to the field |
When content author selects an invalid end date and tries to save the item, the rule will throw an error like this and content author won't be able to save the item without choosing a valid end date.
| Error while saving with an invalid end date |
Note: If we didn't make the class of validation rule as Serializable, when we select the validation button from review tab it will throw an error.
| Validation error message from Validation button |
| Validation error message from Quick action bar |
| Validation error message from Validation bar |
Workflow validation will be done by choosing the validation rule in workflow validation section of field.
Before wrapping up, I would like to mention few more details about Validation Result class. As we see above, content author couldn't save the item because we have given fatal error. There are few more that we can make use of based on the scenario.
| Available validation results |
Happy learning! Thanks for visiting Lean Sitecore!!
Comments
Post a Comment