ValidationMethod Question

Feb 12, 2009 at 11:38 AM
Hi Mike,

Can a ValidationMethod be called via Interception Validation, or does it only get called when using object.Validate() (i.e. state validation)? If I want to do custom validation of a propery via Interception Validation, is the best/only option to define it via a Validation Function (lamda syntax)?

Feb 12, 2009 at 12:21 PM
Methods decorated with the ValidationMethodAttribute perform object validation. These will be invoked when either object.Validate() is called or if an intercepted property/method has the ValidateObject validator registered to it. If I understand correctly, you're asking how to write custom validation functions on property values rather than objects, and this is achieved by writing lambda functions. Object validation using the ValidationMethodAttribute can be explained with the following:

class Dummy
void Foo() {}

Bar Bar{ get; set; }

public static void ValidateDummy(Dummy instance) { ... }


Dummy dummy = new Dummy();

Calling dummy.Foo() will invoke validators registered to typeof(Dummy) passing in the value dummy. The ValidateDummy(...) method will be invoked.
Calling dummy.Bar = new Bar() will invoke validators registered to typeof(Bar).

Feb 12, 2009 at 2:01 PM
Thanks Mike.

One last thing - if I define a lambda function for custom property validation it only gets called during the property setter. I would also like this validation to be used when the object is validated via object.validate (so i dont have to define the validation twice) so I looked at defining it as a static Action<object, IValidationContext> which is then wired up via the static constructor. However, when trying to use that action via a validation method I dont have the validation context to pass to the action?

Is there a better approach?
Feb 12, 2009 at 2:32 PM
If you have state validation enabled (which it should be by default), validation applied to properties will also be invoked when validating the object - so you only have to write and register your validation once. State and Interception validation can be enabled/disabled via the static ValidationSettings class - full info on the [Property Validation Modes] wiki page. You need to register your lambda on the PropertyInfo, not the property setter MethodBase.

The wiki isn't that well structured and I do plan to revisit the documentation sometime soon. Please let me know if you have any other questions.