Validation using attributes

22,137

Here's 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 = "[email protected]";

        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);
        }
    }
}
Share:
22,137
L-Four
Author by

L-Four

Updated on July 05, 2022

Comments

  • L-Four
    L-Four almost 2 years

    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", "[email protected]");
    

    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.