Search code examples
c#validation

c#: Why Validator omitts a ValidationAttribute validation if multiple ValidationAttribute are present?


I have a simple WPF-Application and I use the System.ComponentModel.DataAnnotations.Validator to validate data.

I've created a custom ValidationAttribute which I can set multiple times on a member (AllowMultiple=True).

Simplified something like that:

public class SampleClass
{
    [CustomValidationAttribute("para bla bla")] // as first
    [CustomValidationAttribute("para blu blu")] // as second
    public string MemberA { get; set; }
}

When I now perform Validator.TryValidate(..., true) only the second attribute ("blu blu") is validated, the first, in a magical way, is omitted.

Do I miss something? Or is this a feature? If so, who can I get rid of it?

Thank you for your ideas.

[EDIT 2019-03-12 17:10 CET]

Even when I add an attribute extra, only the validation of the the last one is executed.

public class SampleClass
{
    [CustomValidationAttribute("para bla bla")] // as first
    [CustomValidationAttribute("para blu blu")] // as second
    [CustomValidationAttribute("para bibi")] // as thrid
    public string MemberA { get; set; }
}

"Bibi" is validated, the others not ... Strange, isn't it?


Solution

  • Per Custom validation attribute with multiple instances problem, this can be resolved by uniquely identifying each instance with an override of TypeId:

    public override object TypeId { get; } = new();