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.
Solution
Since the ask was specific to an image field on a template and not to all image fields in general, the first thing that comes to any sitecore developer's mind is using a validation rule on that field inside your template it best suits the purpose. Yes! that is correct, but since there is no default validation rule to use we need to create our very own.
- So, lets start by creating a validation rule item for it within sitecore.
- Go to
/sitecore/system/Settings/Validation Rules/Field Rules
in your sitecore content tree and insert a Validation Rule item by right clicking on the folder and choosing the insert option from there. - You can name the item whatever you want to but for this post we are naming it as
image size limiter and type checker
, you can fill in theTitle
and theDescription
with name of the item for now. - Keep the
Type
and theParameter
field empty for now we will be filling this up later in the post.
- Go to
-
Attach this custom validation rule item on the image field.
- Inside of your template item go to the section where you have your image field item defined. Click on the item.
- Now, scroll down a little on the right until you see the Validation Rule section. Attach your custom validation rule item we just created on all the four multilist that you see. It should look something like this.
- Now, lets write code for our custom validation rule.
- Now, in your app's codebase in .Net create a class(.cs) file and name it
CustomImageSizeValidator
in one of the project inside your solution. In my case it is insideAdx.Foundation.SitecoreFields.Field_Validations
whereAdx.soln
is my solution's name. - Let's create a basic structure of our validation rule file with all the required member functions.
- Now, in your app's codebase in .Net create a class(.cs) file and name it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.Data.Items;
using Sitecore.Globalization;
using Sitecore.Data.Fields;
using Sitecore.Data.Validators;
using Sitecore;
using Sitecore.Collections;
namespace Adx.Foundation.SitecoreFields.Field_Validations {
public class CustomImageSizeValidator: StandardValidator {
public CustomImageSizeValidator() {}
public override string Name {
get {
return "Image Size and Type Validator";
}
}
protected override ValidatorResult GetMaxValidatorResult() {
return GetFailedResult(ValidatorResult.Error);
}
protected override ValidatorResult Evaluate() {
Field field = GetField();
if (field == null) {
return ValidatorResult.Valid;
}
long maxSize = GetMaxSizeFromParameters(); // fetch maxSize from the Parameters
List < string > extensions = GetExtensionsFromParameters();
ImageField imageField = (ImageField) field;
// Get the MediaItem from the ImageField
if (imageField != null && imageField.MediaItem != null) {
MediaItem mediaItem = new MediaItem(imageField.MediaItem);
// In case the extension parameter is not provided
if (extensions.Count == 0) {
extensions.Add(mediaItem.Extension);
}
if (mediaItem != null && mediaItem.Size <= maxSize && extensions.Contains(mediaItem.Extension)) {
return ValidatorResult.Valid;
} else if (mediaItem != null && mediaItem.Size <= maxSize) {
Text = Translate.Text("The image is not of {0} type.", string.Join(",", extensions));
} else if (mediaItem != null && extensions.Contains(mediaItem.Extension)) {
Text = Translate.Text("The image size exceeds the allowed limit of {0}.", MainUtil.FormatSize(maxSize));
} else {
Text = Translate.Text("The image size exceeds the allowed limit of {0} and image is not of {1} type.", MainUtil.FormatSize(maxSize), string.Join(",", extensions));
}
} else {
return ValidatorResult.Valid;
}
return GetFailedResult(ValidatorResult.Error);
}
private long GetMaxSizeFromParameters() {
// Read the custom parameters from the validation rule item's Parameters field
SafeDictionary < string > parameters = GetParameters();
if (parameters != null && parameters["maxSize"] != null) {
return long.Parse(parameters["maxSize"]);
}
// If parsing fails, use a default value
return 1048576; // 1 MB
}
private List < string > GetExtensionsFromParameters() {
List < string > extensions = new List < string > ();
// Read the custom parameters from the validation rule item's Parameters field
SafeDictionary < string > parameters = GetParameters();
if (parameters != null && parameters["extensions"] != null) {
extensions = parameters["extensions"].Split(',').ToList();
}
return extensions;
}
private SafeDictionary < string > GetParameters() {
// Access the Parameters property of the base Validator to get the parameters defined in the validation rule item.
return base.Parameters;
}
}
}
- GetParameters( ) inherits the base Parameter property which holds all the parameters defined in our validation rule items within sitecore.
- GetMaxSizeFromParameters( ) method is created to get the maxSize parameter from the Parameter field on our custom validation rule item within sitecore.
- Similarly, GetExtensionsFromParameters( ) method is created to get the extensions from the Parameter field on our custiom validation rule item within sitecore.
- Evaluate( ) method is called whenever an operation is performed on the image field to which our custom validation rule is attached.
- Now, that our logic is in place lets head back to sitecore and set the remaining fields on our custom validation rule item.
-
Type: In my case the namespace with the class name is
Adx.Foundation.SitecoreFields.Field_Validations.CustomImageSizeValidator
fill yours accordingly. -
Parameters:
maxSize=1048576&extensions=png,jpg&Result=FatalError
fill in the required parameters and I am usingResult=FatalError
parameter to prevent user from saving the item if the validation fails.
-
Type: In my case the namespace with the class name is
- We are all set! Now you can go to any item created from that template and try voilating the validations we just defined on the image field in it.
Note: By default image field have the alt
text validation rule set up which takes severity and displays first. After adding the alt text upon saving you can see our validation displaying if there is any voilation.
PS: Thank you for following up I hope this was of some help if yes pls consider dropping a comment down below, It helps me be motivated to drive this through😄.
Top comments (2)
Great insights 👏🏻and mentioned points can be really helpful for new leaners too
Thank You :)