Attribute Validation

I will 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. For this to work, you need the actual instance of the object you want to check.

But now I want to check a specific value without an instance of the User class, for example:

 TryValidateValue(typeof(User), "EmailAddress", "test@test.com"); 

The goal is that I want to check the value before actually creating an instance of the object itself (the reason is that I allow the creation of valid domain objects). So actually I want to use validation attributes for classes instead of instances.

Any ideas how to do this?

Thanks!

EDIT: So far, I have decided not to use data annotations, but instead use http://fluentvalidation.codeplex.com so that the validation goes beyond entities. Thus, a check can be initiated both inside the objects and for my command handlers. The check itself also looks more readable thanks to good notation.

+8
c # validation asp.net-mvc-3 domain-driven-design data-annotations
source share
1 answer

Here is an example of how you could use the TryValidateValue method:

 public class User { [Required(AllowEmptyStrings = false, ErrorMessage = "EmailIsRequired")] public string EmailAddress { get; set; } } class Program { static void Main() { var value = "test@test.com"; var context = new ValidationContext(value, null, null); var results = new List<ValidationResult>(); var attributes = typeof(User) .GetProperty("EmailAddress") .GetCustomAttributes(false) .OfType<ValidationAttribute>() .ToArray(); if (!Validator.TryValidateValue(value, context, results, attributes)) { foreach (var result in results) { Console.WriteLine(result.ErrorMessage); } } else { Console.WriteLine("{0} is valid", value); } } } 
+16
source share

All Articles