UPDATE 2019-11-12: This article is still valid for Sitecore 9.x
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:
-
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:
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.
Pingback: Sitecore Validators: Validating image width, height and aspect ratio « Brian Pedersen’s Sitecore and .NET Blog
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.
LikeLike
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
{
///
///
///
/// 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
{
///
///
/// The args.
public void Process(SaveArgs args)
{
ProcessInternal(args);
}
///
///
/// 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;
}
}
}
}
}
}
LikeLike
Pingback: Sitecore: Создаём Validation Rule - Rikki Mongoose
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?
LikeLike
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.
LikeLike
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?
LikeLike
@mickeyrahman: Do you have the workflow validation action associated with that workflow command?
LikeLike
@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..
LikeLike
Pingback: My simple Sitecore development framework – Version 1.7 – Walking on clouds
Pingback: Playing around with Sitecore custom validators per template – Walking on clouds
Pingback: Sitecore Validators: Validating image width, height and aspect ratio – Angel's Place