Sunday, 1 November 2015

Custom Sitecore Rich Text Field Max Length Validator

Leave a Comment
Recently I have stumbled upon in a situation where I have to implement Max Length validation on Rich Text Field of a template so that content editor cannot enter more text. For this restriction, I’ve created a Custom Sitecore Rich Text Field Max Length Validator and configured the validator to rich text field. Main thing to be noted about requirement is that html markup should be excluded while length counting and only actual text length should be validated.  Below are the steps of creating a custom validator:
  1. Create an empty assembly project using Visual Studio.
  2. Add the following assembly references to your project:
    a) Sitecore.Kernel
    b) Sitecore.Client
    c) System.Web
  3. Create a new class CustomMaxLengthFieldValidator and write below code in class.
    using Sitecore;
    using Sitecore.Data.Validators;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace SitecoreRichTextMaxLengthValidation
    {
           /// <summary>
        /// Represents a MaxLengthFieldValidator.
        /// </summary>
        [Serializable]
        public class CustomMaxLengthFieldValidator : StandardValidator
        {
            /// <summary>
            /// Gets the name.
            /// </summary>
            /// <value>The validator name.</value>
            public override string Name
            {
                get
                {
                    return "Max Length";
                }
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="T:SitecoreRichTextMaxLengthValidation.CustomMaxLengthFieldValidator" /> class. 
            /// </summary>
            public CustomMaxLengthFieldValidator()
            {
            }
    
            /// <summary>
            /// Initializes a new instance of the <see cref="T:SitecoreRichTextMaxLengthValidation.CustomMaxLengthFieldValidator" /> class. 
            /// </summary>
            /// <param name="info">
            /// The serialization info.
            /// </param>
            /// <param name="context">
            /// The context.
            /// </param>
            public CustomMaxLengthFieldValidator(SerializationInfo info, StreamingContext context)
                : base(info, context)
            {
            }
    
            /// <summary>
            /// When overridden in a derived class, this method contains the code to determine whether the value in the input control is valid.
            /// </summary>
            /// <returns>
            /// The result of the evaluation.
            /// </returns>
            protected override ValidatorResult Evaluate()
            {
                int num = MainUtil.GetInt(base.Parameters["maxlength"], 0);
                if (num <= 0)
                {
                    return ValidatorResult.Valid;
                }
                string controlValidationValue = GetControlValidationValue();
                if (string.IsNullOrEmpty(controlValidationValue))
                {
                    return ValidatorResult.Valid;
                }
                if (controlValidationValue.Length <= num)
                {
                    return ValidatorResult.Valid;
                }
                string[] fieldDisplayName = new string[] { base.GetFieldDisplayName(), num.ToString() };
                base.Text = base.GetText("The maximum length of the field \"{0}\" is {1} characters.", fieldDisplayName);
                return base.GetFailedResult(ValidatorResult.FatalError);
            }
    
            /// <summary>
            /// Gets the max validator result.
            /// </summary>
            /// <remarks>
            /// This is used when saving and the validator uses a thread. If the Max Validator Result
            /// is Error or below, the validator does not have to be evaluated before saving.
            /// If the Max Validator Result is CriticalError or FatalError, the validator must have
            /// been evaluated before saving.
            /// </remarks>
            /// <returns>
            /// The max validator result.
            /// </returns>
            protected override ValidatorResult GetMaxValidatorResult()
            {
                return base.GetFailedResult(ValidatorResult.FatalError);
            }
    
            protected override string GetControlValidationValue()
            {
                return Sitecore.StringUtil.RemoveTags(base.GetControlValidationValue());
            }
        }
    }
    
  4. Compile your assembly and put it in the /bin folder of your website.
  5. Create a new folder User Defined at location /sitecore/system/Settings/Validation Rules/Field Rules/ in master database.
  6. Create a new validation rule RichTextMaxLength by using template /sitecore/templates/System/Validation/Validation Rule at location /sitecore/system/Settings/Validation Rules/Field Rules/User Defined/
  7. Change the default value of the "Type" field to SitecoreRichTextMaxLengthValidation.CustomMaxLengthFieldValidator,SitecoreRichTextMaxLengthValidation. The type format is "<namespace>.<class name>, <assembly name>".
  8. In "Parameters" field enter MaxLength=100. MaxLength value is configurable and change it as per your requirement.

  9.    To configure validation rules for a specific data template field:
    a) In the Template Manager or the Content Editor, select the data template field definition item.
    b) In the Template Manager or the Content Editor, in the Validation Rules section, configure field validation rules.
  10. Now create a sample item and verify if everything works well. You will see below error while saving item if field is having more than 100 characters.

Source code is available at github. Comments and suggestions are most welcome. Happy coding! 
Read More...