.NET 4 RTM MetadataType attribute ignored when using Validator

Posted by bart on Stack Overflow See other posts from Stack Overflow or by bart
Published on 2010-04-17T05:20:40Z Indexed on 2010/04/17 5:23 UTC
Read the original article Hit count: 562

Filed under:
|
|

I am using VS 2010 RTM and trying to perform some basic validation on a simple type using MetadataTypeAttribute. When I put the validation attribute on the main class, everything works. However, when I put it on the metadata class, it seems to be ignored. I must be missing something trivial, but I've been stuck on this for a while now.

I had a look at the Enterprise Library validation block as a workaround, but it doesn't support validation of single properties out of the box. Any ideas?

class Program
{
    static void Main(string[] args)
    {
        Stuff t = new Stuff();

        try
        {
            Validator.ValidateProperty(t.X, new ValidationContext(t, null, null) { MemberName = "X" });
            Console.WriteLine("Failed!");
        }
        catch (ValidationException)
        {
            Console.WriteLine("Succeeded!");
        }
    }
}

[MetadataType(typeof(StuffMetadata))]
public class Stuff
{
    //[Required]  //works here
    public string X { get; set; }
}

public class StuffMetadata
{
    [Required]  //no effect here
    public string X { get; set; }
}

© Stack Overflow or respective owner

Related posts about validation

Related posts about .net-4.0