I have, let's say, this simple class:
public class User
{
[Required(AllowEmptyStrings = false, ErrorMessage="EmailIsRequired"]
public string EmailAddress { get; set; }
}
I know how to use Validator.TryValidateProperty and Validator.TryValidateObject in the System.ComponentModel.DataAnnotations namespace. In order for this to work, you need an actual instance of the object you want to validate.
But now, I want to validate a certain value without an instance of the User class, like:
TryValidateValue(typeof(User), "EmailAddress", "test@test.com");
The goal is that I want to test a value before actually having to instantiate the object itself (the reason is that I only allow valid domain entities to be created). So in fact I want to use validation attributes on classes instead of instances.
Any ideas how that could be done?
Thanks!
EDIT: meanwhile I decided not to use data annotations, but instead use http://fluentvalidation.codeplex.com so that validation is moved outside of the entities. This way validation can be triggered from within the entities as well as my command handlers. The validation itself looks more readable too, thanks to the fluent notation.