views:

23

answers:

1

I would like to be able to validate an object in different contexts using DataAnnotations in .NET 4.

For example: If I have a class with these annotated properties

[Required]
public string Name { get; set; }

[Required]
public string PhoneNumber { get; set; }

[Required]
public string Address { get; set; }

I would like to be able to do something like

bool namePhoneValid = Validator.TryValidateObject(entity, contextNamePhone, results1);
bool allValid = Validator.TryValidateObject(entity, contextAll, results2);

where contextNamePhone only validates Name and Phone, and contextAll validates all properties (Name, Phone and Address in this case).

Is this possible? How should the validation context be constructed? Are there other/smarter ways to do this?

A: 

You can add custom attribute to your class, use type reflection to obtain attribute content at run-time, then write your own validator to validate property against different conditions.

http://oreilly.com/catalog/progcsharp/chapter/ch18.html

ZEAXIF