Enforce alt text for image fields in Sitecore

Alt text in images have their unique place with regard to accessibility and search engine optimization. Seeing as search engines cannot read images or any possible text in them, the only way for the crawlers to find ‘relevant’ images using alt text set on them.

Sitecore by default, does mark image fields which point to images without alt texts set on them with a red flag, but that being said, the content author can choose to just ignore this red flag and move forward and save / publish the item.

Which is why it made perfect sense when a client asked if we could implement a way by which a user would be prevented from saving an item if it used an image with no alt text set on it.

We created a custom field rule and associated this with the image type – this meant that this rule applied to all images in the site. You could also choose to apply the validation rule on individual fields on templates.

The custom validation code, basically used the same code that the default alt validation code which sitecore comes with uses, with the exception of the severity of the error. In our code we set it to a higher level, that would not just warn the content author – but would also prevent them from saving the item at all.

In sitecore:

2014-11-04_042939

There are no config changes involved here. You only need to ensure that the fully qualified class name and the assembly name are included as above.

Here is where we set this validator to all image fields:
2014-11-04_043037

Here’s the code used in the custom validator:

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Data.Validators;
using System;
using System.Runtime.Serialization;
using Sitecore.Diagnostics;
using Sitecore.Shell.Applications.ContentEditor;

namespace *****************._Classes.*************.Customizations.Customized_Sitecore
{
    [Serializable]
    public class ImageAltValidator : StandardValidator
    {
        public ImageAltValidator(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {

        }

        public ImageAltValidator()
        {

        }

        public override string Name
        {
            get { return "ImageAltValidator"; }
        }

        protected override ValidatorResult Evaluate()
        {
            ItemUri itemUri = this.ItemUri;

            if (itemUri == (ItemUri) null)
                return ValidatorResult.Valid;

            Field field = this.GetField();
            if (field == null)
                return ValidatorResult.Valid;

            string str1 = field.Value;
            if (string.IsNullOrEmpty(str1) || string.Compare(str1, "<image />", StringComparison.InvariantCulture) == 0)
                return ValidatorResult.Valid;
            XmlValue xmlValue = new XmlValue(str1, "image");
            string attribute = xmlValue.GetAttribute("mediaid");
            string str2;
            if (!str1.StartsWith("/"))
                str2 = string.Empty;
            else
                str2 = "/sitecore/media library/" + str1.TrimStart(new char[1]
                {
                    '/'
                });

            string path = str2;

            if (string.IsNullOrEmpty(attribute) && string.IsNullOrEmpty(path) || !string.IsNullOrEmpty(xmlValue.GetAttribute("alt")))
                return ValidatorResult.Valid;

            Database database = Factory.GetDatabase(itemUri.DatabaseName);
            Assert.IsNotNull((object) database, itemUri.DatabaseName);
            MediaItem mediaItem = (MediaItem) (!string.IsNullOrEmpty(attribute) ? database.GetItem(attribute, itemUri.Language) : database.GetItem(path, itemUri.Language));
            if (mediaItem == null || !string.IsNullOrEmpty(mediaItem.Alt))
                return ValidatorResult.Valid;

            this.Text = this.GetText("Alternate text is missing in the Image field \"{0}\".", new string[1]
            {
                field.DisplayName
            });
            return this.GetFailedResult(ValidatorResult.FatalError);
        }

        protected override ValidatorResult GetMaxValidatorResult()
        {
            return base.GetFailedResult(ValidatorResult.FatalError);
        }
    }
}

Alternately, you could set this to any specific field:
2014-11-04_043709

So now, when a content author tries to save an item which has an image missing its alt text:
2014-11-04_044040

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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