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);
這也會給你驗證的細節。