Sitecore Custom Field Validators

In many cases developers rely on the content editors to input valid content. In reality that never happens. The only way to protect ourselves from receiving invalid data from Sitecore is by using validators. Sitecore has pretty nice “out of the box” validation rules for common scenarios. But common scenarios are much like unicorns and the guys in Sitecore know that. Because of that there is a pretty nice way to add our own custom validators. It can be achieved in 3 easy steps.

The scenario described in this example is the following: There is a single line text field which should contain exactly 16 characters. The first 8 characters must be numbers and the other 8 characters must be English alphabet letters. (Please keep in mind this can be implemented via the built in Sitecore.Data.Validators.FieldValidators.RegexValidator).

Step 1 – Creating A Custom Validator

Create a Custom Validator that inherits from StandardValidator with the following code.

using Sitecore.Data.Validators;
using System.Text.RegularExpressions;

namespace Sandbox.Validators
{
    public class SandboxIDValidator : StandardValidator
    {
        private readonly Regex numbersRegex = new Regex(@"^\d+$");
        private readonly Regex lettersRegexnew = new Regex(@"^[A-Za-z]+$");

        protected override ValidatorResult Evaluate()
        {
            string value = base.GetControlValidationValue();

            if (!string.IsNullOrEmpty(value) && value.Length == 16)
            {
                string firstPart = value.Substring(0, 8);
                string secondPart = value.Substring(8, 8);

                if (numbersRegex.IsMatch(firstPart) && lettersRegexnew.IsMatch(secondPart))
                {
                    return ValidatorResult.Valid;
                }
            }

            base.Text = "Text is not a valid Sandbox ID";

            return base.GetFailedResult(ValidatorResult.Error);
        }

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

        public override string Name
        {
            get { return "Sandbox ID Validator"; }
        }
    }
}

To create a custom validator, the StandardValidator abstract class should be inerited (which inherits the BaseValidator abstract class). The Name property is self descriptive. The evaluate method gets called when the field needs validation. It determines if the value of the field is valid and and in case it is – it should return ValidatorResult.Valid. Otherwise it should return a validation error of some kind (it might be a suggestion or warning) and error message. GetMaxValidator result is best explained by decompiling the Sitecore.Kernel and looking at the remark:

GetMaxValidatorResult

 

Step 2 – Creating a Sitecore Validation Rule

After the code is ready the validator needs to be added as a Validation Rule in Sitecore. The field validators are located under “/sitecore/system/Settings/Validation Rules/Field Rules/”. The new validation rule for the custom validator should look like this.

Creating_a_custom_validator

Step 3 – Attaching the Validator to a Field

In order to use the validator it should be attached to a field. To attach it navigate to the Template Field in the Template. After that expand the Validation Rules section and add it under the appropriate sections where the validator should appear.AttachToItem

At the end the result should look like this:

ValidatedItem

Happy Validating !

 

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: