Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Data Annotation Validators in Winforms?

I like the Validation Application Block from the Enterprise Library :-)
Now i would like to use the DataAnnotations in Winforms, as we use asp.net Dynamic Data as well. So that we have common technologies over the whole company.
And also the Data Annotations should be easier to use.

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

like image 929
Peter Gfader Avatar asked Dec 16 '08 09:12

Peter Gfader


1 Answers

I adapted a 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));
    }
}

This would allow you to use the following code to validate any object using the following syntax:

var errors = DataValidator.Validate(obj);

if (errors.Any()) throw new ValidationException();
like image 68
Matt Murrell Avatar answered Nov 15 '22 05:11

Matt Murrell