我在纯C#应用程序的项目中使用DataAnnotations,对DataAnnotations属性验证模型/文档的最佳方法是什么?
This is now build into C# 4
var result = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(Vehicle, new ValidationContext(Vehicle, null, null), result);
This will also give you the details of the validation.
Not from me but my friend 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);
}
}
You might need to enhance this, for example if you want [DataType(DataType.EmailAddress)] to actually validate email addresses, or if you want to support the [MetadataType] attribute.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.