IValidate – Validation and custom logic upon publishing pages

My EPiServer site has a specific Settings page where you set general parameters for the web site. These are often placed in the StartPage – parameters like site title, locations of certain pages, etc. Depending on the site and the number of settings, I often place these settings onto a separate PortalSettingsPage.

In my case, I want to add a validation for the PortalSettingsPage. It will check if certain values are valid plus it will save some of these settings to the database where I have a special table for them.

In a normal .Net environment I would place these settings in a web.config file, but since these settings change sometimes and the site is in Azure, I decided to have them in an EpiServer page. But to add further complexity to the issue, my site also needs to read some of these settings on the PortalSettingsPage quite early – when loading the solution and when the code does not yet have access to the EPiServer content itself. So I also want to write a duplicate of these values to the database.

There are other workarounds to this problem, but I found this to be the least cumbersome to implement.

I created a Validation class, and inside the validation, upon a successful one, I can now add the code to update the database with. This is just a sample, with no real logic behind it (..=> I would not save the SiteTitle this way in real life, but it’s the sample that counts here.)

   public class PortalSettingsPageValidator: IValidate<PortalSettingsPage>
    {
        IEnumerable<ValidationError> IValidate<PortalSettingsPage>.Validate(PortalSettingsPage PortalSettingsPage)
        {
            
            
            if (string.IsNullOrEmpty(PortalSettingsPage.SiteTitle))
            {
                yield return new ValidationError()
                {
                    ErrorMessage = "The site title cannot be empty.",
                    PropertyName = PortalSettingsPage.GetPropertyName(x => x.SiteTitle),
                    Severity = ValidationErrorSeverity.Error,
                    ValidationType = ValidationErrorType.AttributeMatched
                };
            }
            else
            {
                // Save the settings to the database here.
            }
        }

    }
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s