Validating data from a class

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

+4
source share
2 answers

Not from me, except 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 may need to improve this, for example, if you want [DataType (DataType.EmailAddress)] to actually check email addresses or want to support the [MetadataType] attribute.

+6
source

Now it is built into C # 4

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

It will also give you detailed verification information.

+13
source

Source: https://habr.com/ru/post/1308335/


All Articles