Sitecore Sunday Pt 4: Conditional (Rules Based) Field Validators

Sitecore’s OOTB field validators are used on pretty much every Sitecore implementation I’ve seen in the last 10 years, which makes it a pretty useful feature! However there are times when there is a little more context surrounding whether or not a particular field is valid.

Thankfully Sitecore makes it super simple to create custom field validators where we have reign to do pretty much whatever we want and there have been some interesting ones put out there for example this image width, height and aspect ratio validator by Brian Pedersen.

I will be calling this approach IFTTV (If This Then Valid).

If This Then Valid

Sorry.

To setup field validator items that use the rules engine we first of course need a template with the necessary validation fields. Sitecore actually already provides this template:

/sitecore/templates/System/Validation/Rules Validation Rule

However this template is intended for use with item level validation that reads from rules under the item:

/sitecore/system/Settings/Rules/Validation Rules/Rules

I feel this approach is disconnected from the management of field validation rules under:

/sitecore/system/Settings/Validation Rules/Field Rules

But we can still take advantage of the template. The first step is to create a template that inherits from the Rules Validation Rule template and specifies our field level rules implementation in the type field.

If This Then Valid Template

The implementation is fairly straight forward:


using Sitecore.Data.Validators;
using Sitecore.Rules;
using Sitecore.Rules.Validators;
using System.Runtime.Serialization;

public class IfThisThenValid : StandardValidator
{
    public override string Name => "If This Then Required";

    public IfThisThenValid()
    {
    }

    public IfThisThenValid(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }

    protected override ValidatorResult Evaluate()
    {
        var item = GetItem();

        if (item == null)
            return ValidatorResult.Valid;

        var ruleContext = new ValidatorsRuleContext
        {
            Item = item,
            Validator = this,
            Result = ValidatorResult.Valid,
            Text = string.Empty
        };

        var validatorItem = item.Database.GetItem(ValidatorID);

        if (validatorItem == null)
            return ValidatorResult.Valid;

        var rules = RuleFactory.GetRules<ValidatorsRuleContext>(new[] { validatorItem }, "Rule");

        if (rules == null)
            return ValidatorResult.Valid;

        rules.Run(ruleContext);

        if (ruleContext.Result == ValidatorResult.Valid)
            return ValidatorResult.Valid;

        base.Text = ruleContext.Text;

        return base.GetFailedResult(ruleContext.Result);
    }

    protected override ValidatorResult GetMaxValidatorResult()
    {
        // Critical or above (Fatal) is important for experience editor support

        return base.GetFailedResult(ValidatorResult.CriticalError);
    }
}

To summarise:

  • Inherit from Sitecore’s StandardValidator
  • Get the item being validated (rules are run against this as the context item)
  • Get the validator item (this is where our rules live)
  • Get the rules in the validator item and run them against the context item using a ValidatorsRuleContext (which returns a ValidationResult). This is where the difference lies from Sitecore’s standard implementation*, which evaluates the context item against the rules under: /sitecore/system/Settings/Rules/Validation Rules/Rules
  • Return the result

*Sitecore.Data.Validators.ItemValidators.ValidationRulesValidator,Sitecore.Kernel

Then I will create a folder under /sitecore/system/Settings/Validation Rules/Field Rules and an insert options rule so we can create new rules based field validators and organise them in folders:

If This Then Valid Insert Options

As an example I added two fields to the Sample Item template, Sitecore Image and External Image, the validation scenario is at least one of them must be provided. Here’s our rule based validator:

If This Then Valid Rule

Which is associated with our fields on the sample item:

If This Then Valid Field

And here’s it in action:

If This Then Valid Usage

And that’s it, pretty straight forward but a ton of uses, especially considering the extensibility of the rules engine.

Happy validating!

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 )

Google+ photo

You are commenting using your Google+ 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