We have implemented a page validator using the IValidator interface. The problem is that this is triggered every time the page is autosaved - raising an error. Which is quite frustrating to say the least. How can we arrange so that the validator only kicks in when publishing the page?
For now the option is to not implement IValidate<T> (since then the validator will be automatically registered) and instead explicitly call your validator from an eventhandler to IContentEvents.PublishingContent and throw an exception if it is not valid.
I have reported a bug that validation should be done after the pre events have been raised because then you could have a boolean property called something like IsPublishing on your base class for pages. You could decorate the property with Ignore attribute to not get a backing property data for it.
Then you could attach an eventhandler to IContentEvents.PublishingContent and in the event handler set the property IsPublishing to true. Then in your validator class you can do the validation only if IsPublishing is true.
I am having the same problem as this when trying to validate a block type. I have tried testing for the item ID being greater than zero. At creation its ID will be zero. So my Validate() method looks like this:
IEnumerable<ValidationError> IValidate<SoundCloudBlock>.Validate(SoundCloudBlock instance)
var contentItem = instance as IContent;
if (contentItem.ContentLink.ID > 0)// Test if it has been created yet
/* ..... */
Can anybody see anything wrong with this?