Sitecore 6 Validators

One of the cool features in Sitecore 6 is the ability to include validators on your fields. Any field can contain any number of validators, validating anything from the validity of the
HTML to the number of characters in a string.
And as always, Sitecore have made the validators completely open for developers to create their own validators.

So – lets make one. This small example will check to see if a text contains bad language (the actual bad language checker is not implemented – I’ll mark it in the code).

First I’ll create a new class that derives from Sitecore.Data.Validators.StandardValidator. Note that the whole class is Serializable. Sitecore uses this when the user cliks on the “Validate” button (the button with the icon shaped as a bug).

using System;
using System.Text;

using Sitecore.Data.Validators;

namespace Pentia

{
  [Serializable]
  public class LanguageValidator : StandardValidator
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="LanguageValidator"/> class.
    /// </summary>
    public LanguageValidator(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="LanguageValidator"/> class.
    /// </summary>
    public LanguageValidator()
    {
    }

    /// <summary>
    /// Gets the name of the validator.
    /// </summary>
    /// <value>The name.</value>
    public override string Name
    {
      get { return "LanguageValidator"; }
    }

    /// <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()
    {
      // Get the value to validate
      string controlValidationValue = base.ControlValidationValue;
      // !!! Write your own bad language validator here !!!
      if (ContainsBadLanguage(controlValidationValue)
      {
        base.Text = "The text contains bad language";
        retrn ValidatorResult.CriticalError;
      }
      return ValidatorResult.Valid;
    }

    /// <summary>
    /// Gets the max validator result.
    /// </summary>
    /// <returns>The max validator result.</returns>
    /// <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>
    protected override ValidatorResult GetMaxValidatorResult()
    {
      return base.GetFailedResult(ValidatorResult.CriticalError); 
    }
  }
}

That’s it. The “Name” property tells Sitecore what the name of the validator is. The Evaluate() function will evaluate the contents of the field. The GetMaxValidatorResult() tells Sitecore what the maximum error level is. You have 6 levels of validation to play with: Valid (do nothing), Suggestion (yellow color), Warning (orange color), Error (red color), CriticalError (also red) and FatalError. A CriticalError or FatalError will disable saving of the item.

The return text is set using the base.Text attribute, but I could also have used the base.Errors array. In the above example, it could be a nice feature to return the word that causes the validator to fail. I’ll rewrite my business logic:

string[] badWords = GetBadWords(controlValidationValue);
if (badWords.Count > 0)
{
  foreach (string word in badWords)
  {
    base.Errors.Add(word + " is a bad word and must be removed before saving");
  }
  return ValidatorResult.CriticalError;

}
return ValidatorResult.Valid;

It is very easy to install the validator. No web.config changes are needed. Just copy the validator DLL to the /bin/ directory of the web site and create a new validator under /system/settings/Validation Rules/Field Rules. You may also add your validator directly on a field type. This is done under /system/settings/Validation Rules/Field types.

Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in Sitecore 6 and tagged , . Bookmark the permalink.

6 Responses to Sitecore 6 Validators

  1. Pingback: Using Sitecore Field Validators « Brian Pedersen’s Sitecore and .NET Blog

  2. Pingback: Sitecore Validators: Validating image width, height and aspect ratio « Brian Pedersen’s Sitecore and .NET Blog

  3. Pingback: Sitecore Validators: Validating image width, height and aspect ratio | CMS News Today

  4. mickeyrahman says:

    I love your blog! Very clearly and nicely communicated…

  5. Mike says:

    Just the information I was looking for

  6. Huy Tran says:

    OK, Thanks so much

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