English 中文(简体)
Validating a class using DataAnnotations
原标题:

I have a class that I am using to model my data in MVC. I have added some DataAnotations to mark fields that are required and I am using regular expressions to check valid Email Addresses. Everything works fine if the object is posted back to MVC and I have the ModelState property that I can check to confirm that the class is valid but how do I check to see if the class is valid outside of MVC using the same class and Data Anotations that I have already set up?

最佳回答

Here s a method that I ve used in the past with Data Annotations to get all of the errors on an annotated object (it could use some improvements, but it s 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);    
}
问题回答

There doesn t appear to be anything built into .NET 3.5. If you can develop against .NET 4, though, there is a Validator class that provides what you need:

Validator class on MSDN





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签