Gigi Cocorsicanu
Gigi Cocorsicanu

Reputation: 1

Why ValidationAttribute.IsValid is called later than expected?

I have a property annotated with a validation attribute. Why is the setter on the property called before the IsValid method of the attribute, and more importantly how do i get it to validate before setting the value ?

Here is a sketched code model to see how the validator attribute looks like:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MyAttribute: ValidationAttribute
{       
    public override bool IsValid(object value) 
    {
        ...
    }
}

Here is how the attribute is used on the property:

[MyAttribute]
public string MyProperty
{
   get { ... }
   set { ... }
}

Upvotes: 0

Views: 852

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

I assume you're talking about the ValidationAttribute within the DataAnnotations namespace? These attributes are used to generally describe validation requirements, without any particular prescribed model.

But, in many cases, it makes sense for an object or set of objects to be constructed, and then for a call to be made to ask "Is this now valid?" - so, of course, in such a case, the call to your IsValid method will occur well after the value of the property was set.

Attributes, in general, are passive - until such time as something actually accesses the attribute programatically and does something with it, none of your code within the attribute will run. There's no general way to write an attribute that says "when the member that this attribute is attached to is invoked, run this piece of code first".

Upvotes: 1

Related Questions