39

I'm trying to validate a class decorated with data annotation with the Validator class.

It works fine when the attributes are applied to the same class. But when I try to use a metadata class it doesn't work. Is there anything I should do with the Validator so it uses the metadata class? Here's some code..

this works:

public class Persona
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "El nombre es obligatorio")]
    public string Nombre { get; set; }

    [Range(0, int.MaxValue, ErrorMessage="La edad no puede ser negativa")]
    public int Edad { get; set; }
}

this doesnt work:

[MetadataType(typeof(Persona_Validation))]
public class Persona
{
    public string Nombre { get; set; }
    public int Edad { get; set; }
}

public class Persona_Validation
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "El nombre es obligatorio")]
    public string Nombre { get; set; }

    [Range(0, int.MaxValue, ErrorMessage = "La edad no puede ser negativa")]
    public int Edad { get; set; }
}

this is how I validate the instances:

ValidationContext context = new ValidationContext(p, null, null);
List<ValidationResult> results = new List<ValidationResult>();

bool valid = Validator.TryValidateObject(p, context, results, true);

thanks.

FlyingFoX
  • 3,379
  • 3
  • 32
  • 49
Pablote
  • 4,745
  • 9
  • 39
  • 46
  • I cannot find ValidationContext within System.ComponentModel.DataAnnotations (MVC 2.0) Am I doing something wrong? – Myster Jul 21 '10 at 23:24
  • @Myster check that System.ComponentModel.DataAnnotations.dll is referenced in the project. – Pablote Jul 24 '10 at 02:33
  • Simply use this [gist](https://gist.github.com/JimmyBoh/b7c135820c18a06648a5) (an extension method) and you can call p.Validate() – Dilhan Jayathilake May 05 '17 at 03:02

2 Answers2

50

I found the answer here: http://forums.silverlight.net/forums/p/149264/377212.aspx

MVC recognizes the MetaDataType attribute, but other projects do not. Before validating, you need to manually register the metadata class:

TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Persona), typeof(Persona_Validation)), typeof(Persona));

ValidationContext context = new ValidationContext(p, null, null);
List<ValidationResult> results = new List<ValidationResult>();

bool valid = Validator.TryValidateObject(p, context, results, true);
Jeremy Gruenwald
  • 1,947
  • 1
  • 19
  • 18
  • I expanded on my answer to similar question here: http://stackoverflow.com/questions/1755340/validate-data-using-dataannotations-with-wpf-entity-framework/2467387#2467387 – Jeremy Gruenwald Oct 13 '10 at 17:13
  • 1
    The `validateAllProperties` flag tripped me up. Its worth remembering to set that where appropriate! – Gusdor Oct 24 '17 at 09:21
  • @JeremyGruenwald , **ValidationContext** is not working for collections. Can you please help me out? – Jayakrishnan Nov 28 '17 at 12:08
  • @JayakrishnanGounder, I haven't done this hands-on in years now, sorry. Are you trying to validate each object in a collection, or the collection itself as a property of a parent object (e.g. collection cannot be empty)? For the former, I would hope it would work to apply the same logic to the objects contained in the collection. For the latter, I think you'd probably have to write your own business logic. – Jeremy Gruenwald Nov 29 '17 at 17:20
-1

Try to move the metadata class into the same namespace as the Persona class if it isn't already. I was having similar problems and moving my metadata class into the same namespace as the L2S model class worked for me.

Dzejms
  • 3,108
  • 2
  • 30
  • 40