来自类的DataAnnotationsvalidation

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

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

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

这也将为您提供validation的详细信息。

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

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

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