来自类的DataAnnotations验证

Cop*_*ill 4 c# data-annotations

我在一个纯C#应用程序的项目中使用DataAnnotations,根据DataAnnotations属性验证模型/文档的最佳方法是什么?

Nat*_*ugg 14

现在这已经构建到C#4中

var result = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(Vehicle, new ValidationContext(Vehicle, null, null), result);
Run Code Online (Sandbox Code Playgroud)

这也将为您提供验证的详细信息.


Cop*_*ill 6

不是我,而是我的朋友Steve Sanderson:

internal static class DataAnnotationsValidationRunner
{
    public static IEnumerable<ErrorInfo> GetErrors(object instance)
    {
        return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
               from attribute in prop.Attributes.OfType<ValidationAttribute>()
               where !attribute.IsValid(prop.GetValue(instance))
               select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能需要增强此功能,例如,如果您希望[DataType(DataType.EmailAddress)]实际验证电子邮件地址,或者您希望支持[MetadataType]属性.