sukesh
sukesh

Reputation: 2425

How to pass parameters to a custom validator in Sitecore

I have a custom validator class to validate a General Link field type. It checks that the field value of the Description field is not more than 15 characters.
But what if a Link field of same or another template, requires 20 chars.

Is there a way, I can pass the integer as a parameter. If so, how to pass & use it.
Also, can it be done at the base Template's field level. (so that I can define limits for each such field)

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);
    }
   }
}

Upvotes: 0

Views: 1296

Answers (2)

Vlad Iobagiu
Vlad Iobagiu

Reputation: 4118

Plese check next class: is verifing maxlength of a field by template This rule is assigned to a field.

[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);
    }

}

Upvotes: 2

Marek Musielak
Marek Musielak

Reputation: 27132

Just see how regex validator is used to validate email:

enter image description here

You add parameters and read them in Validator code later:

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);
}

Upvotes: 3

Related Questions