Validate object instead of MyClass

Topics: Validation Application Block
Jan 24, 2007 at 6:38 AM

I'm trying to centralize validation code and would like to do the following:


When I do that no validation is performed. I have to do the following:


to get any validation done.

How can I do this validation without having to know the classname of obj at compile time?

Jan 24, 2007 at 4:58 PM
Hi Herbjörn -

It's not possible to do this in the current CTP, however a very simple code change will enable this (and we're going to make this change ourselves so this will work in future versions).

In ValidationFactory there is an internal method
internal static Validator CreateValidator(Type targetType, string ruleset)

If you change this to public, you should be able to get what you want by calling

Validator v = ValidationFactory.CreateValidator(obj.GetType(), null);
ValidationResults results = v.Validate(obj);

Is this what you want?
Jan 24, 2007 at 5:38 PM
I am not sure I understand the problem. Is your object of type MyClass or a derived class, and what class is associated with the validation rules for the object?

For example, this works fine and is similar to your example:

public class Customer
public string Name { get; set; }

Customer obj = new Customer();
obj.Name = null;

ValidationResults results = Validation.Validate(obj);

The class type is inferred, albeit you could do:

ValidationResults results = Validation.Validate<Customer>(obj);

I haven't tried it yet with an object hierarchy, which I will do today, but otherwise it should work fine.




David Hayden
Microsoft MVP C#
Jan 25, 2007 at 12:32 PM

Thanks for Your answers!

What I want is what Tom suggests.

If I call the
instead of the
as Dave suggests no validation will be done unless obj is cast to the MyClass type.

I want to centralize all validation and not have to worry about the type of objects that is to be validated.