2

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?

7
  • Maybe the first one is overloaded with the second custom validator? Commented Mar 11, 2019 at 15:24
  • @GabrielCostin Not sure if I understand you correctly: You assume, the first attribute is replaced with the second one? Commented Mar 12, 2019 at 16:05
  • Yes that's what I am assuming, in fact you can try with another attribute, for exemple StringLength , define 2 or more attributes and check the output Commented Mar 13, 2019 at 7:25
  • Confirmed: The behavior is, that only the last declared validation attribute each type is used for validation. This knowledge is nice, but back to topic: How can I change that behavior? I find it very strange, that same-type-attributes are just swallowed, up instead an aproppriate exception is thrown ... Commented Mar 13, 2019 at 12:42
  • Well I am not that experienced to offer you a very good solution , what I would do is just like create that CustomValidationAttribute and maybe instead of having a string as parameter type I would go for an array of strings or whatever Commented Mar 13, 2019 at 14:16

1 Answer 1

0

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - that's the solution. If I got some time, I will check if out-of-the-box attributes, which uses allowmultipe=true. also use this technique =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.