Validation using attributes

拜拜、爱过 提交于 2019-12-03 06:13:50

问题


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.


回答1:


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 = "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);
        }
    }
}


来源:https://stackoverflow.com/questions/7926693/validation-using-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!