Context dependent validation
- by Ole Lynge
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?