7

I would like to Validate the Image Field say i shouldn't allow the image more than 1 MB. How do I do that in content editor?

3

As Mark Cassidy explained, you can only achieve this via the implementation of a custom validation rule. Please see below the code for the custom validation.

[Serializable]
public class ImageWeightDynamicValidator : StandardValidator
{
    public int Weight;

    public override string Name
    {
        get
        {
            return "ImageWeightDynamicValidator";
        }
    }
    protected override ValidatorResult Evaluate()
    {
        ItemUri = ItemUri;
        var field = GetField();
        if (Parameters.ContainsKey("Weight"))
        {
            Weight = MainUtil.GetInt(Parameters["Weight"], 0);
        }

        var str = field.Value;

        if (string.IsNullOrEmpty(str))
        {
            return ValidatorResult.Valid;
        }

        if (string.CompareOrdinal(str, "<image />").Equals(0))
        {
            return ValidatorResult.Valid;
        }

        var database = Factory.GetDatabase(ItemUri.DatabaseName);

        Assert.IsNotNull(database, ItemUri.DatabaseName);
        var attribute = new XmlValue(str, "image").GetAttribute("mediaid");

        MediaItem item = database.GetItem(attribute);

        if (string.IsNullOrEmpty(attribute))
        {
            item = Context.Database.Items[$"/sitecore/media library/{str}", LanguageManager.GetLanguage(ItemUri.Language.Name, Context.Database)];

            if (item == null)
            {
                return ValidatorResult.Valid;
            }
        }

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

        var size = item.Size;

        var mediaSizeKb = ConvertBytesToKilobytes(size);

        if (mediaSizeKb > Weight)
        {
            Text = Translate.Text("The image referenced in the Image field \"{0}\" is too big. Max size is \"{1}\" kB", field.DisplayName, Weight.ToString(CultureInfo.InvariantCulture));

            return GetFailedResult(ValidatorResult.FatalError);
        }

        return ValidatorResult.Valid;
    }

    private static double ConvertBytesToKilobytes(long bytes)
    {
        return (double)bytes / 1024;
    }

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

    private ValidatorResult GetResult(string text, params string[] arguments)
    {
        Text = GetText(text, arguments);
        return GetFailedResult(ValidatorResult.Error);
    }

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        if (info == null)
            throw new ArgumentNullException(nameof(info));

        base.GetObjectData(info, context);
    }

    protected ImageWeightDynamicValidator(SerializationInfo info, StreamingContext context) : base(info, context)
    {
        if (info == null)
        {
            throw new ArgumentNullException(nameof(info));
        }
    }
}

Once the code has been set into the solution, you need to create the validation rule item.

  1. Navigate to the path /sitecore/system/Settings/Validation Rules/Field Rules/

  2. Create a Validation Rule Item (Right-click -> Insert -> Validation Rule).

  3. Fill in the item fields as shown in the screenshot below.

enter image description here

Note that you only need to change the Type to match your Namespace and Assembly name and also the Weight in the Parameter fields. Right now it is set to 1. 1 is in KB.

  1. Assign the validation rule to your field in the template. You can read the link provided by Mark Cassidy in his answer or this one. This will help on how to set the validation on the field.
7

The setting

Well there isn't really a built in validator for this; although you could build one.

But you can - generally - restrict the size of media in your solution. It is controlled via this setting:

<setting name="Media.MaxSizeInDatabase" value="500MB" />

Setting it to 1MB would restrict your content authors from uploading large media.

The alternative

Rather than restricting media like this, a better option (in my opinion) is to make sure all your images are web-optimised when Sitecore sends them to the client.

There are several solutions for this; my preference would be Dianoga - An automatic image optimizer for the Sitecore media library.

2
  • Hi Mark , Thanks for your answer.Is there any way to validate a specific template ?I need it it in only one template not the whole site – Prakash Jun 15 '17 at 5:03
  • Unfortunately not. Not without some custom coding. The setting I mention here, is global. – Mark Cassidy Jun 15 '17 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.