Validating a class using DataAnnotations

I have a class that I use to model my data in MVC. I added some DataAnotations to mark the fields that are needed, and I use regular expressions to check for valid email addresses. Everything works fine if the object is sent back to MVC, and I have a ModelState property that I can check to confirm that the class is valid, but how to check if the class is really valid outside MVC using the same class and Data Anotations that I already set up?

+3
source share
2 answers

Here is a method that I used in the past with Data Annotations to get all errors in an annotated object (it may use some improvements, but this is a good starting point:

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);    
}
+2
source

In .NET 3.5 nothing is embedded. If you can evolve against .NET 4, then there is a Validator class that provides what you need:

Validator Class on MSDN

0
source

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


All Articles