This is the first post in a series about back to basics. All to often I come across Sitecore projects that commit a number of sins. Hopefully this will tie together with the continuing series on working with the Sitecore platform instead of against it. So with that in mind, the first few parts will be about field validation in Sitecore.
Field validation is often overlooked. I think in part because the template editor has a quick and dirty interface for setting all the common properties such as name, source, shared etc. But to setup the validation, help text and the like you have to go into the field itself.
However, the content editors experience can be greatly enhanced with good validation with clear, concise error messages. It also means that as developers, we can enforce a little safety in our environment and increase our chances that our code will get data in the right ‘shape’.
A short history lesson
Before Sitecore 5, validation was done with regular expressions and a generic error message. This would fire and the user would see a popup with that message. After a while this would get pretty annoying as the editor couldn’t really see which fields were invalid and, in some cases, the warning wasn’t a critical error. Inevitably, unless all of the fields were required and the error messages could be made verbose enough, validation was turned off.
Even now Sitecore 7.x supports this functionality but using it is an incredibly bad idea.
Sitecore validation done right
Validation done right means you need to use the validators built into Sitecore (or add your own) using the various multi-lists directly on the field item for your template. If you do so, you have the advantage that as the editor builds their content, they get visual cues as to which field is incorrect. This appears as a red bar next to the field and colour spots to the top right (in the content editor). You also have the advantage that you can set the levels of these errors and class some as critical meaning the user can’t progress without fixing and you can make others ‘a bad idea’.
More importantly, these are all written in .NET code. What this means is that when you write your own, you’ll be able to unit test them under various conditions and more easily have them as part of your continuous integration builds.
This post was particularly short as an introduction to validators but they are more of a ‘show me the code’ topic. Its also pretty near to Christmas and I have small people to entertain! 🙂
In my next post on this topic, I’ll look at writing a very simple validator, registering it with Sitecore and setting its error level. More importantly, we’ll look at making it have different options per language and so handle some interesting scenarios. We’ll also have a unit test setup for it and I’ll put it on Github for reference.