2

I wanted to set image size validation for an image field for example the image field should not accept any image more than 2 mb. For this I tried using Image Size validator available in Sitecore.

Item Path:

/sitecore/system/Settings/Validation Rules/Field Rules/System/Image Size

The parameter field was set to "maxSize = 2MB" But this is not working. How to make use of this validator to validate image size? How to set the parameter field value?

enter image description here

1
  • finally, at the end how did you approach it ? Commented Jul 20, 2023 at 7:25

2 Answers 2

2

I decompile the code of : Sitecore.Data.Validators.FieldValidators.ImageSizeValidator and I see in the validator is verifing if the size of the image field is bigger then value of MaxSizeinMemory and MaxSizeInDatabase settings. These 2 are stored in the Sitecore.config file.

   <!--  MEDIA - MAX SIZE IN DATABASE
        The maximum allowed size of media intended to be stored in a database (binary blob).
        This value must be less than the ASP.NET httpRuntime.maxRequestLength setting.
        Default value: 500MB
  -->
<setting name="Media.MaxSizeInDatabase" value="500MB" />

and 

 <!--  MEDIA - MAX SIZE IN MEMORY
        The maximum size of media to load into memory for processing (resizing etc.).
        Default value: 40MB
  -->
<setting name="Media.MaxSizeInMemory" value="40MB" />

Here is the code which is validating the size of image.

if (size > Settings.Media.MaxSizeInMemory)
        {
            base.Text = this.GetText("The image referenced in the Image field \"{0}\" is too big to be resized.", new string[]
            {
                field.DisplayName
            });
            return base.GetFailedResult(ValidatorResult.Warning);
        }
        if (size > Settings.Media.MaxSizeInDatabase)
        {
            base.Text = Translate.Text("The image referenced in the Image field \"{0}\" is too big to be stored in the database.", new object[]
            {
                field.DisplayName
            });
            return base.GetFailedResult(ValidatorResult.Warning);
        }

To test this validator you need to change that values to a lower value or add an image which is bigger than 40 MB.

0

If you are finding a way to create a custom validation rule in Sitecore to handle this on a specific image field on a template then you can consider my brief answer in a dedicated blog here. The Ask or the Task to achieve is listed below - the solution for which I have provided in the blog itself.

Ask

The requirement was to limit image size on a image field in any template and also to restrict the type of image.

For example: The image should be less then 1 MB & should be either png or jpg.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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