Using Sitecore Field Validators

The Sitecore field validators is a set of user-input validators that can be applied to either an item, a specific field type or a specific field on a specific item.

Sitecore comes standard with a set of validators, including broken links validation, email validators, max length validators and XHTML/W3C validation. You can find all validation rules at /sitecore/system/settings/validation rules:

Validator rules
Validator rules
The folder “Field Rules” contains rules to be applied at individual fields on individual templates. “Field types” contains validation rules from the Field Rules folder applied to each field type. By applying rules to a field type you ensure that every field of this type is validated with the rules applied. “Global Rules” applies to all items and grabs its validations from “Item Rules“.
 
You apply rules to fields on individual items by selecting the field on a template to apply validation. Select the Validation Rules secion and select the rules to apply in the fields “Quick Action Bar” (applies validation to the left of the field), “Validate Button” (validation is run when clicking the Validation button on the Review tab), “Validator Bar” (applies validaton to the bar at the right of the fields) and the “Workflow” (applies validation when workflow is running).
 
Applying validator rules to a field on a template

Applying validator rules to a field on a template

 
Many of the validations can be configured individually, and all validators have at least one parameter called “Result” which determines what the default result of the validator must be:
 
Validator parameters

Validator parameters

Parameters are applied using a QueryString-like list like this:
 
[parameter]=[value]&[parameter]=[value]
 
The “Result” paremeter determines the default result value of a validation. Possible values are:
  • Valid = Green, everything is fine
  • Suggestion = Bright Orange, hmm, take a look at this
  • Warning = Orange, you should do something about this
  • Error = Red, this is an error you know
  • CriticalError  = Red, user is warned before saving
  • FatalError = Red, user cannot save item before validator is cleared

While returning Valid on a validation error makes no sense, the FatalError can be used to stop the user from saving an item before the issue is resolved, like in this example:

Validator returning FatalError

Validator returning FatalError

You can also (fairly easily) create your own validators. See this post about Sitecore 6 Validators.

Validation Rules should be applied when necessary. Do not overdo your validation rules as it might complicate the life of the people editing the website rather than helping them.

Remember that it is often quicker to clean up after bad editing instead of applying rule on rule on rule to stop them doing a specific thing. For example you might have a design that is good looking if the tile of the page is max. 30 characters. So you apply a rule saying that if the title is longer than 30 chars the user cannot save the page. But really, what would happen if the title is 31 chars? Or 40? Does the web site stop working or does the design fail? And what if the title contains a lot of small letters (i, l, j, …)? Then the title may look fine even with 35 chars.

Validations should support and help your editor, not hinder then in their work.

 
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 .net, Sitecore 6 and tagged , , , , . Bookmark the permalink.

9 Responses to Using Sitecore Field Validators

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

  2. Chris Brady says:

    how can you adjust the alert prompt to actually report the fields containing the errors and generally enrich the dialog box? thx.

    Something like:

    The item has the following errors, which must be fixed before you may save this item:
    – Please specify at least one author for this article
    – Please add 5 tags to this article
    – etc.

    Ideally, these errors would take you to the field in the content editor as well.

  3. briancaos says:

    You can rewrite the saveUI pipeline processor step. You need to rewrite this processor step:

    [processor mode="on" type="Sitecore.Pipelines.Save.Validators, Sitecore.Kernel" /]

    This is an exmaple of a new processor that sums up all fields in the dialog box and explains each error individually:

    #region

    using System.Text;
    using Sitecore;
    using Sitecore.Data;
    using Sitecore.Data.Items;
    using Sitecore.Data.Validators;
    using Sitecore.Diagnostics;
    using Sitecore.Pipelines.Save;
    using Sitecore.Web;
    using Sitecore.Web.UI.Sheer;

    #endregion

    namespace PT.Framework.FieldValidators
    {
    ///

    /// Class to replace the processor in the saveUI pipeline.
    ///

    ///
    /// This class fixes the annoying Danish tranalation issue (by not translating at all but having all texts in danish)
    /// but also adds a list of validator texts that explains which fields have which errors when the error message
    /// is critical or fatal error.
    ///
    internal class SaveUI
    {
    ///

    /// Processes the specified args.
    ///

    /// The args.
    public void Process(SaveArgs args)
    {
    ProcessInternal(args);
    }

    ///

    /// Processes the internal.
    ///

    /// The args.
    protected void ProcessInternal(ClientPipelineArgs args)
    {
    Assert.ArgumentNotNull(args, "args");
    if (args.IsPostBack)
    {
    if (args.Result == "no")
    {
    args.AbortPipeline();
    }
    args.IsPostBack = false;
    }
    else
    {
    string formValue = WebUtil.GetFormValue("scValidatorsKey");
    if (!string.IsNullOrEmpty(formValue))
    {
    ValidatorCollection validators = ValidatorManager.GetValidators(ValidatorsMode.ValidatorBar, formValue);
    ValidatorOptions options = new ValidatorOptions(true);
    ValidatorManager.Validate(validators, options);
    ValidatorResult valid = ValidatorResult.Valid;
    StringBuilder sb = new StringBuilder();
    foreach (BaseValidator validator in validators)
    {
    ValidatorResult result = validator.Result;
    if (validator.ItemUri != null)
    {
    Item item = Client.ContentDatabase.GetItem(validator.ItemUri.ToDataUri());
    if (((item != null) && StandardValuesManager.IsStandardValuesHolder(item)) &&
    (result > ValidatorResult.CriticalError))
    {
    result = ValidatorResult.CriticalError;
    }
    }
    if (result > valid)
    {
    valid = validator.Result;
    }
    if (validator.IsEvaluating && (validator.MaxValidatorResult >= ValidatorResult.CriticalError))
    {
    SheerResponse.Alert(
    "Validation has not yet completed.\n\nWait until all the validators have completed and then save again.",
    new string[0]);
    args.AbortPipeline();
    return;
    }
    // This is the part that is different from Sitecore.Pipelines.Save.Validators.
    // Here i collect all validator texts in a stringbuilder so I can display the validation results
    if (validator.Result == ValidatorResult.CriticalError || validator.Result == ValidatorResult.FatalError)
    {
    sb.AppendLine(string.Format("{0} : {1}", validator.GetFieldDisplayName(), validator.Text));
    }
    }
    switch (valid)
    {
    // Here I display the collected validation texts and display them in the dialog boxes:
    case ValidatorResult.CriticalError:
    SheerResponse.Confirm("Siden har felter med kritiske fejl.\n\nEr du sikker på at du vil gemme?\n\n" + sb);
    args.WaitForPostBack();
    break;

    case ValidatorResult.FatalError:
    SheerResponse.Alert("Siden indeholder fejl. Du kan ikke gemme før du har rettet følgende fejl:\n\n" + sb,
    new string[0]);
    args.AbortPipeline();
    break;
    }
    }
    }
    }
    }
    }

  4. Pingback: Sitecore: Создаём Validation Rule - Rikki Mongoose

  5. mickeyrahman says:

    I have a question: So in sitecore, when you create a new item, the values are all coming from standard values (if they have it set). If they don’t have some of those fields set, they are empty. But by the time you created the item, the item with the empty fields are already created. So how you can prevent the user from leaving the item until all the validation rules have been met?

  6. briancaos says:

    The validation rules kick in when saving an item, not when creating it.
    Example: You have set the “Title” as a required field, with validation result “FatalError” (item cannot be saved before validation is met).
    If you leave the “Title” blank in the __Standard Values, the item will be blank when created. At this point, the user will not be able to save OR navigate to another item, before the “Title” is filled out. The only way out would be to forcibly close the internet browser.

  7. mickeyrahman says:

    Thanks! – So now that I created the validator, (it works) – I inherited from StandardValidator. So now, I want to run it when a user tries to switch from one workflow state to another. I put the rule to hit in the workflow section of the standard values of the item, but its not running (not hitting the validator at all…. am I missing something?

  8. John West says:

    @mickeyrahman: Do you have the workflow validation action associated with that workflow command?

  9. @john: yes, I’ve figured it out since then – the issue was that the validation action would fire only if the max warning level exceeds the setting you create when you create the validation action. I understood that as to be the max warning level it could fire (ever)… so I had set it to maximum. But it being maximum, the warning status level returned never exceeded it, so never fired..

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