Validate object instead of MyClass

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

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

Validator.Validate(obj);

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

Validator.Validate((MyClass)obj);

to get any validation done.

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

Sincerely
Herbjörn
Jan 24, 2007 at 5: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?
Tom
Jan 24, 2007 at 6: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
{
NotNullValidator
StringLengthValidator(1,200)
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.

Regards,

Dave

________________________

David Hayden
Microsoft MVP C#
http://www.davidhayden.com/
Jan 25, 2007 at 1:32 PM
Hi,

Thanks for Your answers!

What I want is what Tom suggests.

If I call the
Validation.Validate(obj);
instead of the
Validation.Validate<MyClass>(obj);
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.

Sicerely
Herbjörn