Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c# - Validating DataAnnotations with Validator class

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.

question from:https://stackoverflow.com/questions/2050161/validating-dataannotations-with-validator-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...