Sitecore Image Size Validator

In most sites, by design we have some minimum image size requirements which the content authors need to adhere by while uploading content images to maintain the integrity of the design.

In our project we wanted to add a validation in place so that the content author wouldn’t be allowed to set images smaller than what minimum requirement was set by the front end designers.

In some cases, we also needed to enforce an exact dimensions match, so we included the provision for that as well.

Here’s how we went about this:

We created a new template to use here – Base Image Validation
2015-09-17_233234

And added this new template as a base for the Template Field template:

2015-09-17_233428

So now, these fields would be available on all template fields. Even though these fields will be available in all template fields, the validation logic we hook up, will be fired only for image field types.

So here’s the code we need to hook up the validation logic:

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

        }

        public ImageSizeValidator()
        {

        }

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

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

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

            Field field = 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[]
                {
                    '/'
                });

            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(database, itemUri.DatabaseName);
            Item mediaItem = !string.IsNullOrEmpty(attribute) ? database.GetItem(attribute, itemUri.Language) : database.GetItem(path, itemUri.Language);
            Item fieldItem = database.GetItem(field.ID, itemUri.Language);

            if (mediaItem == null || IsValidDimensions(mediaItem, fieldItem))
                return ValidatorResult.Valid;

            Text = GetText("Selected image in the field \"{0}\" does not match the size restrictions "
                + (SitecoreHelper.ItemRenderMethods.GetCheckBoxValueByFieldName("Exact Dimensions Match", fieldItem)
                ? "(Width:{1}, Height:{2})" : "(Minimum Width:{1}, Minimum Height:{2})"), new[]
            {
                field.DisplayName,
                fieldItem.Fields["Minimum Width"].Value,
                fieldItem.Fields["Minimum Height"].Value
            });
            return GetFailedResult(ValidatorResult.FatalError);
        }

        private bool IsValidDimensions(Item mediaItem, Item fieldItem)
        {
            int validationHeight, validationWidth, imageWidth, imageHeight;

            int.TryParse(fieldItem.Fields["Minimum Width"].Value, out validationWidth);
            int.TryParse(fieldItem.Fields["Minimum Height"].Value, out validationHeight);
            int.TryParse(mediaItem.Fields["Width"].Value, out imageWidth);
            int.TryParse(mediaItem.Fields["Height"].Value, out imageHeight);

            if (SitecoreHelper.ItemRenderMethods.GetCheckBoxValueByFieldName("Exact Dimensions Match", fieldItem))
            {
                if ((validationHeight == 0 && validationWidth == 0)
                || (validationHeight == 0 && validationWidth > 0 && validationWidth == imageWidth)
                || (validationHeight > 0 && imageHeight == validationHeight && validationWidth == 0)
                || (validationWidth > 0 && validationHeight > 0 && validationWidth == imageWidth && validationHeight == imageHeight))
                {
                    return true;
                }
            }
            else if ((validationHeight == 0 && validationWidth == 0)
                || (validationHeight == 0 && validationWidth > 0 && validationWidth <= imageWidth) || (validationHeight > 0 && validationHeight <= imageHeight && validationWidth == 0) || (validationWidth > 0 && validationHeight > 0 && validationWidth <= imageWidth && validationHeight <= imageHeight))
            {
                return true;
            }

            return false;
        }

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

And we then created a new validation rule item in Sitecore and pointed it to this method in our assembly:

2015-09-17_234518

This rule then needs to be added to the image field item, depending upon what actions you would like to trigger the validations at, the rule will need to be added accordingly. Eg. Quick Action Bar / Validate Button / Validation Bar:

2015-09-18_001320

As an example, consider this field where the validations have been set at:

2015-09-18_002701

So uploading an image smaller than this would result in the error state:

2015-09-18_002909

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