4
我在一个纯C#应用程序的项目中使用DataAnnotations,根据DataAnnotations属性验证我的模型/文档的最佳方法是什么?DataAnnotations从类验证
我在一个纯C#应用程序的项目中使用DataAnnotations,根据DataAnnotations属性验证我的模型/文档的最佳方法是什么?DataAnnotations从类验证
不:
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.EmailAddress)实际验证的电子邮件地址,以提高这一点,例如,或者如果你想以支持[MetadataType]属性。
现在这是建设成C#4
var result = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(Vehicle, new ValidationContext(Vehicle, null, null), result);
这也会给你验证的细节。