Validator.ValidateObject(…) ignores MetadataType attributes

Just spent a couple of hours trying to get to the bottom of this. :(
Basically, if you have a generated-code class (like in entity framework), the easiest way to add validation is to use MetadataType in the partial class (because you can’t add attributes to the generates properties – you would lose them if the code gets regenerated).

[MetadataType(typeof(JobMetadata))]
partial class Job : IGuidID
{
	public class JobMetadata
	{
		[Required]
		public global::System.String Title { get; set; }
	}
...
}

When using ASP.NET MVC’s ModelState.IsValid and the default MVC validation, everything goes as expected – the [Required] attribute is respected and you get the appropriate validation error message.

Now, if you need to run the validation manually, using Validator.[Try]ValidateObject(…), you’re in for a nasty surprise: the validation passes, ignoring your attributes.
After a lot of searching, I finally narrowed it down to MetadataType, got the right search terms and found the answer on Stack Overflow (of course): you need to manually register the MetadataType provider.

static Job()
{
	TypeDescriptor.AddProviderTransparent(
			new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Job), typeof(JobMetadata)), typeof(Job));
}

Here is the link for the full answer.

This entry was posted in Gotcha. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>