Validating DataAnnotations with Validator class
Posted
by Pablote
on Stack Overflow
See other posts from Stack Overflow
or by Pablote
Published on 2010-01-12T15:45:28Z
Indexed on
2010/03/11
19:39 UTC
Read the original article
Hit count: 589
I'm trying to validate a class decorated with dataannotation 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.
© Stack Overflow or respective owner