Validating DataAnnotations with Validator class

32,346

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);
Share:
32,346
Pablote
Author by

Pablote

Updated on March 17, 2020

Comments

  • Pablote
    Pablote over 4 years

    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.

  • Pablote
    Pablote over 14 years
    It didnt work, I've also tried putting the metadata class inside the class, but no luck.
  • Jeremy Gruenwald
    Jeremy Gruenwald over 13 years
    I expanded on my answer to similar question here: stackoverflow.com/questions/1755340/…
  • Gusdor
    Gusdor over 6 years
    The validateAllProperties flag tripped me up. Its worth remembering to set that where appropriate!
  • Jayakrishnan
    Jayakrishnan over 6 years
    @JeremyGruenwald , ValidationContext is not working for collections. Can you please help me out?
  • Jeremy Gruenwald
    Jeremy Gruenwald over 6 years
    @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.