1. Create the custom field validation rule in Sitecore
2. Create a class in a class library project for your code. The class should inherit from Sitecore.Data.Validators.StandardValidator
public class UniqueValueValidator : StandardValidator
{
protected override ValidatorResult Evaluate()
{
string parent = this.Parameters["parent"];
string value = base.GetControlValidationValue();
string query = string.Format("{0}//*[@{1} = '{2}']", parent, this.GetFieldDisplayName(), value);
foreach (Item item in global::Sitecore.Data.Database.GetDatabase("master").SelectItems(query))
{
//skip the current item
if (item.ID != base.GetField().Item.ID)
{
//set the error message
Text = GetText("Value must be unique. Item \"{0}\" contains the same value in field \"{1}\".", new[]{ item.DisplayName, GetFieldDisplayName()});
return ValidatorResult.Error;
}
}
return ValidatorResult.Valid;
}
protected override ValidatorResult GetMaxValidatorResult()
{
return GetFailedResult(ValidatorResult.Warning);
}
public override string Name
{
get
{
return "UniqueValue";
}
}
}
It is important to note that having a custom validator in place will not prevent an editor from creating items with duplicate field values. All it will do is provide feedback, so the solution should still be able to handle duplicate field values if they do appear.
No comments:
Post a Comment