Sitecore Rich Text Field (RTF) length validator

In some cases, to maintain the integrity of the design, we might want to restrict the amount of text that the content author can add in the rich text field. For this purpose we created a custom validator and applied the same to rich text fields only.

For single line / multiline fields, this can be easily achieved by simply using regex patterns for validation, with rich text fields, the presence on html, requires more custom logic.

Please note – you can also disallow certain tags in the custom validation code here, like images / canvas / picture etc, if the design calls for it.

We first added a field for the maximum length, to the Template Field item (/sitecore/templates/System/Templates/Template field). which would make this field available in all template fields.

2015-09-18_014147

Following is the code used for the custom validation, which uses this field:

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Data.Validators;
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;

namespace sc72.Customizations.Sitecore
{
    [Serializable]
    public class RichTextLengthValidator : StandardValidator
    {
        public RichTextLengthValidator(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {

        }

        public RichTextLengthValidator()
        {

        }

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

        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))
                return ValidatorResult.Valid;

            Database database = Factory.GetDatabase(itemUri.DatabaseName);
            Item fieldItem = database.GetItem(field.ID, itemUri.Language);
            int maxLength;

            if (!(fieldItem.Fields["Maximum Length"] != null && !string.IsNullOrWhiteSpace(fieldItem.Fields["Maximum Length"].Value)
                && int.TryParse(fieldItem.Fields["Maximum Length"].Value, out maxLength) && maxLength > 0))
                return ValidatorResult.Valid;

            if (StripHtml(str1).Length > maxLength)
            {
                Text = GetText("Character count '{0}' exceeded the limit '{1}' for field \"{2}\".", new[]
                {
                    StripHtml(str1).Length.ToString(CultureInfo.InvariantCulture),
                    maxLength.ToString(CultureInfo.InvariantCulture),
                    field.DisplayName
                });
                return GetFailedResult(ValidatorResult.FatalError);
            }

            return ValidatorResult.Valid;
        }

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

        public static string StripHtml(string str)
        {
            return Regex.Replace(str, "<.*?>", string.Empty);
        }
    }
}

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

2015-09-18_014346

This rule then needs to be added to the rich text 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_014447

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

2015-09-18_014607

So exceeding the character limit (after stripping off html tags!), would give a fatal error.

2015-09-18_015123

2015-09-18_015109

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