Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Runtime.Serialization;
using Sitecore.Common;
using Sitecore.Data.Items;
using Sitecore.Data.Validators;
using Sitecore.Rules;
using Sitecore.SecurityModel;
using MyProject.Foundation.Validation.Consts;
using MyProject.Foundation.Validation.Rules.Contexts;
namespace MyProject.Foundation.Validation.Validators.Fields.ValidationRules
{
[Serializable]
public class ValidationRulesValidator : StandardValidator
{
public ValidationRulesValidator(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public ValidationRulesValidator()
{
}
public override string Name
{
get { return "Validation Rules"; }
}
protected override ValidatorResult Evaluate()
{
var item = GetItem();
var field = GetField();
if (item == null || field == null)
{
return ValidatorResult.Valid;
}
Item rulesItem;
using (new SecurityDisabler())
{
rulesItem = field.Database.GetItem(SitecoreIds.FieldValidationRules.ToID());
}
if (rulesItem == null)
{
return ValidatorResult.Valid;
}
var validatorsRuleContext = new FieldValidatorsRuleContext
{
Item = item,
FieldValue = GetControlValidationValue(),
FieldId = field.ID,
Validator = this,
Result = ValidatorResult.Valid,
Text = string.Empty
};
var ruleContext = validatorsRuleContext;
var rules = RuleFactory.GetRules<FieldValidatorsRuleContext>(rulesItem, "Rule");
if (rules == null)
{
return ValidatorResult.Valid;
}
rules.RunFirstMatching(ruleContext);
Text = GetText(ruleContext.Text);
return ruleContext.Result == ValidatorResult.Valid ? ValidatorResult.Valid : GetFailedResult(ruleContext.Result);
}
protected override ValidatorResult GetMaxValidatorResult()
{
return GetFailedResult(ValidatorResult.Error);
}
}
}
@sruter
Copy link

sruter commented Jan 15, 2019

Where are the "SitecoreIds" coming from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment