【发布时间】:2011-08-23 01:27:57
【问题描述】:
我在纯 C# 应用程序的项目中使用 DataAnnotations,根据 DataAnnotations 属性验证我的模型/文档的最佳方法是什么?
【问题讨论】:
标签: c# data-annotations
我在纯 C# 应用程序的项目中使用 DataAnnotations,根据 DataAnnotations 属性验证我的模型/文档的最佳方法是什么?
【问题讨论】:
标签: c# data-annotations
现在已内置到 C# 4 中
var result = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(Vehicle, new ValidationContext(Vehicle, null, null), result);
这还将为您提供验证的详细信息。
【讨论】:
不是来自我,而是来自我的朋友史蒂夫·桑德森:
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.EmailAddress)] public object DataTypeTest { get; set; }任何想法为什么?