Search code examples
c#asp.net-mvcvalidationattribute

Placeholder in constructor chaining?


I was going through a material and the code for the custom validation logic is as follows:-

public class MaxAttribute : ValidationAttribute
{
   public MaxAttribute(int maxWords) : base("{0} has too many words.")
   {
       _maxWords = maxWords;
   }
   public override ValidationResult IsValid(object value, ValidationContext validationContext)
   {
       if(value != null)
       {
         var valueAsString = value.ToString();
         if(valueAsString.Split(' ').Length > _maxWords)
         {
           var errorMessage = FormatErrorMessage(validationContext.DisplayName);
           return new ValidationResult(errorMessage);
         }
       }
       return ValidationResult.Success;
   }
       private readonly int _maxWords;
}

It says,

The placeholder exists the call to the inherited FormatErrorMessage method, will automatically format the string using the display name of the property."

I am not able to contemplate just how the flow will be like? All I know is when I type this say,

   [MaxWords(10)]
   public string Name{get;set}

The MaxWordsAttribute(int maxWords) constructor will be called and that will call the base constructor :base({0}...) Just when and how is call to FormatErrorMessage will fill in the placeholder?


Solution

  • The place to look is that call to FormatErrorMessage: that's the place where the error message is constructed. So let's take a look:

    public virtual string FormatErrorMessage(string name) =>
        string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
    

    That ErrorMessageString is the string you passed to the base constructor (in a slightly roundabout way).