0

I have simple program that validate with data anotatoin but when i use MetadataType for seperate data anotation , resualt validation always is true. Why result below code is always true ?

public partial class User
{
    public string FullName { get; set; }
}


[MetadataType(typeof(UserMetadata))]
public partial class User
{
}

public class UserMetadata
{
    [Required]
    [MinLength(2)]
    public string FullName { get; set; }
}

class Program
{
    static void Main(string[] args)
    {

        var u = new User
        {
            // must raise error
            FullName = "A"
        };

        var context = new ValidationContext(u, null, null);
        var list = new List<ValidationResult>();
        var isCorrect = Validator.TryValidateObject(u, context, list, true);

        // isCorrect always is True 
        Console.WriteLine(isCorrect);
        Console.ReadKey();
    }
}
james
  • 19
  • 3

1 Answers1

0

In a MVC project the the MetaDataType attribute gets recognized. Other projects will need a little help. Before you start validating, you will need to register the metadata class.

TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(User), typeof(UserMetadata)), typeof(User));

That should enable you to test your validation correctly.

There's a lot more information on this in a related topic answer from Jeremy Gruenwald -> Validate data using DataAnnotations with WPF & Entity Framework

Community
  • 1
  • 1
Zephire
  • 394
  • 7
  • 16