In this tutorial, you will learn about a handy new feature within Episerver CMS that will allow you to provide different levels of validation and feedback to content editors when they try and save content within the CMS. For example, if they tried to save a page with missing data you might want to trigger a custom error message. This notification system is possible by returning a ValidationErrorSeverity enumeration. The ValidationErrorSeverity comes in four flavours:

  • None

  • Info

  • Warning

  • Error

When you return data in one of these formats, a dialogue will appear next to the publish button within the editor:

Different Validation Warnings To Content Editors 1

There are two ways of adding validation to page types and properties within Episerver:

  • IValidate

  • ValidationAttribute

The focus of this tutorial is on IValidate. If you are interested in the ValidationAttribute I recommend you read How to Create a Custom Content Area Validator in Episerver?.

IValidate

The Episerver.Validation.IValidate<T> interface was introduced in Episerver 7+. To create a custom validation, you create a new class and implement the IValidate<T> interface where T is the page type that you want to associate your new validation rule against. After compiling your site, when your website loads for the first time, Episerver will scan all of your assemblies. Any class that implements IValidate will be registered within the CMS. On page save, based on the page type, all the relevant custom validators will then be called. The IValidate interface implements a method called Validate(). All the associated Validate() methods will need to pass successfully before the CMS is allowed to update the content.

Creating a validator requires minimal code to be written and can be seen below:

As the interface uses generics, within the Validate() method you will get the strongly typed object of type T as a parameter. In Validate() perform any validation on the pages data you wish. If you find an error in the data, 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.


It is as simple as that. To set up some page-level validation, all you need to do is define a single validation class, however, it is very powerful! Happy Coding 🤘