How to use data annotation validators in Winforms?

I like the Application Validation block from the Enterprise Library :-)
Now I would like to use DataAnnotations in Winforms, since we also use asp.net Dynamic Data. So that we have common technologies throughout the company.
As well as data annotations should be easier to use.

How can I do something similar in Winforms, like Stephen Walter did in asp.net MVC ?

+5
source share
1 answer

I adapted the solution found at http://blog.codeville.net/category/validation/page/2/

public class DataValidator
    {
    public class ErrorInfo
    {
        public ErrorInfo(string property, string message)
        {
            this.Property = property;
            this.Message = message;
        }

        public string Message;
        public string Property;
    }

    public static IEnumerable<ErrorInfo> Validate(object instance)
    {
        return from prop in instance.GetType().GetProperties()
               from attribute in prop.GetCustomAttributes(typeof(ValidationAttribute), true).OfType<ValidationAttribute>()
               where !attribute.IsValid(prop.GetValue(instance, null))
               select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty));
    }
}

:

var errors = DataValidator.Validate(obj);

if (errors.Any()) throw new ValidationException();
+9

All Articles