2016-03-16 2 views
0

У меня есть собственный класс валидатора для проверки типа поля General Link. Он проверяет, что значение поля поля Description не превышает 15 символов.
Но что, если поле Link того же или другого шаблона требует 20 символов.Как передать параметры пользовательскому валидатору в Sitecore

Есть ли способ, я могу передать целое число в качестве параметра. Если да, то как пройти & используйте его.
Кроме того, это можно сделать на уровне базового шаблона. (Так что я могу определить пределы для каждого такого поля)

namespace CustomValidators 
{ 
    // This validator ensures that the description attribute of a link is either empty or has length of 15 characters. 
    [Serializable] 
    public class LinkTextValidator : StandardValidator 
    { 
    public override string Name {get { return "Link text validator"; } } 

    public LinkTextValidator() { } 

    public LinkTextValidator(SerializationInfo info, StreamingContext context) : base(info, context) { } 

    protected override ValidatorResult Evaluate() 
    { 
     Field field = this.GetField(); 

     if (field == null) 
     return ValidatorResult.Valid; 

     string fieldValue = this.ControlValidationValue; 

     if (string.IsNullOrEmpty(fieldValue) || string.Compare(fieldValue, "<link>", StringComparison.InvariantCulture) == 0) 
     return ValidatorResult.Valid; 

     XmlValue xmlValue = new XmlValue(fieldValue, "link"); 
     string attribute = xmlValue.GetAttribute("text"); 

     if (!string.IsNullOrEmpty(xmlValue.GetAttribute("text")) && Convert.ToString(xmlValue.GetAttribute("text")).Length > 15) 
     { 
     this.Text = this.GetText("Description field should have not more than 15 characters, in the link field \"{0}\".", field.DisplayName); 
     return this.GetFailedResult(ValidatorResult.FatalError); 
     } 
     else 
     { 
     return ValidatorResult.Valid; 
     } 
    } 

    protected override ValidatorResult GetMaxValidatorResult() 
    { 
     return this.GetFailedResult(ValidatorResult.FatalError); 
    } 
    } 
} 

ответ

3

Просто посмотреть, как регулярное выражение валидатор используется для проверки электронной почты:

enter image description here

Вы добавляете параметры и читать их в Validator код позже:

protected override ValidatorResult Evaluate() 
{ 
    string controlValidationValue = this.ControlValidationValue; 
    if (string.IsNullOrEmpty(controlValidationValue)) 
    return ValidatorResult.Valid; 
    string pattern = this.Parameters["Pattern"]; 
    if (string.IsNullOrEmpty(pattern) || new Regex(pattern, RegexOptions.IgnoreCase).IsMatch(controlValidationValue)) 
    return ValidatorResult.Valid; 
    this.Text = this.GetText("The field \"{0}\" does not match the regular expression \"{1}\".", this.GetFieldDisplayName(), pattern); 
    return this.GetFailedResult(ValidatorResult.Error); 
} 
+0

Параметр передается на уровне «Правило». Если в моем проекте есть 6 типов полей Link, у каждого из которых есть другой предел, тогда у меня должно быть 6 разных правил. я прав? – Qwerty

+0

Да, с этой опцией вы бы имели правило «Максимальная длина 20», а другая «Максимальная длина 10» –

+0

Тогда, в моем случае, мне не нужны параметры, если мне нужно создавать правила для отдельных случаев. правильно? Я хотел знать, можем ли мы передавать параметр на уровне шаблона. Так что будет только один валидатор, но разные параметры. Надеюсь, вы поняли мою озабоченность. – Qwerty

2

проверка Plese следующий класс: как MaxLength проверка наличия поля по шаблону Это правило относится к полю.

[Serializable] 
public class MaxLengthFieldbyTemplateValidator : StandardValidator 
{ 
    /// <summary> 
    /// The template separator in Parameters field 
    /// </summary> 
    private const char FieldLengthSeparator = '='; 

    /// <summary> 
    /// The template length separator in Parameters field 
    /// </summary> 
    private const char TemplateLengthSeparator = '~'; 

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

    /// <summary> 
    /// Initializes a new instance of the <see cref="T:Sitecore.Data.Validators.FieldValidators.MaxLengthFieldValidator"/> class. 
    /// 
    /// </summary> 
    public MaxLengthFieldbyTemplateValidator() 
    { 
    } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="T:Sitecore.Data.Validators.FieldValidators.MaxLengthFieldValidator"/> class. 
    /// 
    /// </summary> 
    /// <param name="info">The serialization info. 
    ///    </param><param name="context">The context. 
    ///    </param> 
    public MaxLengthFieldbyTemplateValidator(SerializationInfo info, StreamingContext context) 
     : base(info, context) 
    { 
    } 

    /// <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() 
    { 
     return IsValid(GetItem().TemplateID.ToString()) ? ValidatorResult.Valid : this.GetFailedResult(ValidatorResult.CriticalError); 
    } 

    private bool IsValid(string currentItemTemplateId) 
    { 
     var validatorParameters = Parameters; 
     // parsing all validators,they are splited by & char 
     foreach (var currentParam in validatorParameters) 
     { 
      //checking if current item template id is in parameters value 
      if (currentParam.Value.Contains(currentItemTemplateId)) 
      { 
       if (currentParam.Value.Contains(TemplateLengthSeparator)) 
       { 
        var maxLenghKeyValuePair = currentParam.Value.Split(TemplateLengthSeparator)[1]; 
        if (maxLenghKeyValuePair.Contains(FieldLengthSeparator)) 
        { 
         var maxLengthValue = maxLenghKeyValuePair.Split(FieldLengthSeparator)[1]; 
         int intMaxLengthValue = MainUtil.GetInt(maxLengthValue, 0); 
         string controlValidationValue = this.ControlValidationValue; 
         if (string.IsNullOrEmpty(controlValidationValue) || 
          controlValidationValue.Length <= intMaxLengthValue) 
         { return true; } 
         else 
         { 
          Text = GetText("The maximum length of the field \"{0}\" is {1} characters.", this.GetFieldDisplayName(), maxLengthValue); 
          return false; 
         } 
        } 
       } 
      } 
     } 
     return true; 
    } 

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

} 
+0

Не могли бы вы рассказать мне, где были определены параметры в дереве контента? – Qwerty

+0

Мне понадобится создать несколько классов Validator для разных полей ссылок !!. Я хочу иметь только один класс Validator, принимающий параметры. Это возможно. – Qwerty

+0

Извините, присвоено поле не шаблону –

Смежные вопросы