In this tutorial you will learn how to add a custom validator onto a content area. On some projects, you may want to add some form of custom validation in your content areas, for example, you may only want to allow 5 blocks in a carousel, or, you only want certain blocks to be allowed.
In Episerver there is no easy way to do it this via the UI. To attempt it would involve writing some dojo. Instead, you can create a custom validation attribute you can add to a content area to apply your rules. If the validation fails, the page won't save and an error message can be displayed back to the user.
To create a validation rule, all you need to do is to create a new class inheriting from ValidationAttributeand override the 2 IsValid methods.
The MaxItemsAllowed attribute can then be used to decorate the content area you care about. This method is probably the way I would recommend going.
Validating using IValidate
As of Episerver 7 there is also another way of validating a content area, this way using the IValidate interface. Create a new class and inherit from IValidate. On application start, EPiServer scans the solution for a class that implements EPiServer.Validation.IValidate and executes the Validate() method.
This works the same way as the Page Type builder model, if a class is decorated as a ContentType, it gets picked up. The IValidate method will be called any time a page or block is saved. In your validate method, you simply specify the page type you want to filter by and then put the code inside it.
That should do you fine. I prefer putting the attribute on the ContentArea class approach as it gives you less code duplication, but both ways work well.