DataAnnotations validation from a class

谁说我不能喝 提交于 2019-11-27 03:06:23

问题


I am using DataAnnotations in a project that is a pure C# application, what is the best way to validate my models/documents against the DataAnnotations attributes?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2736097/dataannotations-validation-from-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!