Try our conversational search powered by Generative AI!

Johan Björnfot
May 22, 2018
  3579
(7 votes)

IContentSaveValidate - validation with context

This time I thought I should share a tip about a component IContentSaveValidate<TContent> that we added a while ago but that perhaps not all are aware of. 

In CMS 7 we added the EPiServer.Validation.IValidate<T> interface, which has a signature like:

 /// <summary>
    /// Defines the signature for a component that validates instances of <typeparamref name="T"/>.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IValidate<T> : IValidate
    {
        /// <summary>
        /// Validates the specified instance.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        IEnumerable<ValidationError> Validate(T instance);
    }

The idea with the interface was to make it possible to extend the validation possibilities offered by validation attributes. So when calling IValidationService.Validate for an item then will the service first locate all registered validators that has a generic type parameter T which the item can be assigned to and then call validate on them. So say for example that we are validating an instance of StandardPage then would validators implementing IValidate<StandardPage>, IValidate<PageData> and IValidate<IContent> be called but not a validator implementing IValidate<IContentMedia>.

The IValidate<T> interface does not have any type constraint but it is most commonly used during save of content instances. However there might be cases where you want to do the validation only for certain state transitions, for example when the content is published. With IValidate<T> it is not possible to distinguish which state transition it is (if any). Therefore we introduced the more specialized interface IContentSaveValidate<TContent> that looks like:

public interface IContentSaveValidate<TContent> : IContextValidate<TContent, ContentSaveValidationContext>
        where TContent : IContentData
    {
        /// <summary>
        /// Validates the specified instance given specified context
        /// </summary>
        /// <param name="instance">The instance that is validate</param>
        /// <param name="context">The context for the validation</param>
        /// <returns>A list of validation errors or empty list if instance is valid</returns>
        IEnumerable<ValidationError> Validate(TContent instance, ContentSaveValidationContext context);
    }

Now in addition to the content item to validate you also get a context where you can get the state transtion from. Below is an example of an implementation that only validates when a StandardPage is published.

    [ServiceConfiguration(IncludeServiceAccessor = false)]
    public class StandarPagePublishedValidator : IContentSaveValidate<StandardPage>
    {
        private readonly IStatusTransitionEvaluator _statusTransitionEvaluator;

        public StandarPagePublishedValidator(IStatusTransitionEvaluator statusTransitionEvaluator)
        {
            _statusTransitionEvaluator = statusTransitionEvaluator;
        }

        public IEnumerable<ValidationError> Validate(StandardPage instance, ContentSaveValidationContext context)
        {
            var transition = _statusTransitionEvaluator.Evaluate(instance, context.SaveAction);
            if (transition.NextStatus == VersionStatus.Published)
            {
                //do validation for publish here
            }
            return Enumerable.Empty<ValidationError>();
        }
    }



May 22, 2018

Comments

Please login to comment.
Latest blogs
The Experimentation Process

This blog is part of the series -   Unlocking the Power of Experimentation: A Marketer's Insight. Welcome back, to another insightful journey into...

Holly Quilter | May 16, 2024

Azure AI Language – Sentiment Analysis in Optimizely CMS

In the following article, I showcase how sentiment analysis, which is part of the Azure AI Language service, can be used to detect the sentiment of...

Anil Patel | May 15, 2024 | Syndicated blog

Optimizely Data Platform Visitor Groups now supports multiple instances

The module V2.0 now supports multiple Optimizely Data Platform instances, allowing personalized content based on real-time segments and profile dat...

Andrew Markham | May 15, 2024 | Syndicated blog

IP block for edit and admin in DXP

Why IP-blocking edit/admin? A hacker can try to guess user names and passwords to gain access to your site. This risk can be minimized in a couple ...

Daniel Ovaska | May 15, 2024

Do not upgrade to EPiServer.CMS.Core 12.21.4 without reading this!

Todays update of EPiServer.CMS.Core 12.21.4 alters default sort order in an unexpected way, when you are working with muligple languages and have...

Tomas Hensrud Gulla | May 14, 2024 | Syndicated blog

Upgrade Optimizely CMS From v11 to v12

Why Upgrade? There are many improvements implemented in version 12, but most importantly is that the whole framework is migrated from .Net Framewor...

MilosR | May 13, 2024