从一个类进行DataAnnotations验证

4

我在一个纯C#应用程序中使用DataAnnotations,如何最好地根据DataAnnotations属性验证我的模型/文档?

2个回答

14

这现在已经集成到C# 4中了

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

这也会给您提供验证的详细信息。


7

以下内容不是我写的,而是我的朋友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);
    }
}

如果您想要[DataType(DataType.EmailAddress)]实际验证电子邮件地址,或者想要支持[MetadataType]属性,您可能需要对此进行改进。


这对我来说适用于除了 DataType 之外的所有属性。例如:[DataType(DataType.EmailAddress)] public object DataTypeTest { get; set; } 有什么想法吗? - Rob McCabe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接