Search code examples
c#.netenterprise-libraryvalidation

Accessing Validator block ErrorMessage


public class Test 
{
    [RelativeDateTimeValidator(-10, DateTimeUnit.Year, 10, DateTimeUnit.Year, ErrorMessage = "Error")]
    public DateTime ADate { get; set; } 

    public void ValidateMyProperty() 
    {
        ADate = new DateTime(1900, 01, 01);

        ValidationResults vrs = Validation.Validate<Test>(this);
        foreach (var vr in vrs)
        {
            Print(vr.Message);
        }
    }
}

this displays

The value must fall within the range "-10"(Year) - "10(Year) relative to now

However, how do I diplay/access the error message that I have specified (ErrorMessage = "Error")?

Thanks in advance.


Solution

  • I think you are looking for the MessageTemplate attribute if you want to specify what the message they receive when validation fails. It allows replaceable tokens too.

    From documentation :

    public class Person
    {
      [RelativeDateTimeValidator(-120, DateTimeUnit.Year, -18, DateTimeUnit.Year,
               Ruleset="RuleSetA", MessageTemplate="Must be 18 years or older.")]
      public DateTime DateOfBirth
      {
        get
        {
          return dateOfBirth;
        }
      }
    }
    

    Message Template Tokens

    If the message template contains tokens (for example, "{0}"), the validator will replace these tokens with values when the ValidationResult is created. The tokens supported by the Relative Date Time Validator are listed in the following table.

    Token

    Meaning

    {0}

    This token represents the value of the object that is being validated. Although it can be useful to show the original value as a part of the validation message, you must be careful to avoid injection attacks by escaping any characters that can be used to attack the system that conveys the message to the user.

    {1}

    This token represents the key of the object that is being validated. When the validator is attached to a member of a type such as a property or a field, the key is set to the member name. When the validator is attached to an object, the key is null and the token is replaced by an empty string.

    {2}

    This token represents the tag that is specified on the validator instance. If no tag is supplied, the token is replaced by an empty string.