In Episerver 7+ developers have been provided with a handy new feature to provide different levels of feedback to content editors when they create new pages and blocks using the ValidationErrorSeverity enumeration. The ValidationErrorSeverity comes in four flavours:
Which, when triggered, a dialogue will appear next to the publish button:
There are two ways of applying validation to page types and properties in Episerver:
In the example above, only IValidate lets you use the warning and info states, so, we will start there. If you are interested in the ValidationAttribute I have written more about it in, How to Create a Custom Content Area Validator in Episerver?
The EPiServer.Validation.IValidate interface was introduced in Episerver 7+. When your website loads for the first time, EPiServer scans all your assemblies. One of the big reasons for doing this is to find all pages and blocks that have been defined in your solution.
It scans for any classes that implement IValidate. If it finds a match it will register the validator against the page type and the classes Validate() method will then be called whenever the type is saved in the editor.
Creating a validator requires minimal code to be written. The code to trigger the screenshot above can be seen below:
In your execute method you get the strongly typed object of the 'thing' you are trying to validate. In here you can then perform any validation on the properties you wish. If you find an error you can then return a ValidationError setting the Severity property to the level you want to. The text added to the ErrorMessage property is the text that will be displayed back to the content editor.
In today's tutorial, we've covered how you can display validation messages to content editors, using the ValidationErrorSeverity enumeration. We have two ways of validating pages and properties, IValidate for validating pages themselves and ValidationAttribute to apply validation to properties.
In today's guide, we've covered all the code required to validate a page in our solution called 'ContentPage' and return a variety of validation message back to the user.