验证的DataAnnotations与Validator类 [英] Validating DataAnnotations with Validator class

查看:460
本文介绍了验证的DataAnnotations与Validator类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证一个类装饰着数据标注的<一个href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator(VS.100).aspx">Validator类。

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

在属性应用于同一类,它工作正常。但是,当我尝试使用元数据类这是行不通的。有什么我应该做的,因此使用元数据类的验证?下面是一些code ..

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..

本作品:

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

这不工作:

[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; }
    }

这是我如何验证实例:

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

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

感谢。

推荐答案

我找到了答案在这里:<一href="http://forums.silverlight.net/forums/p/149264/377212.aspx">http://forums.silverlight.net/forums/p/149264/377212.aspx

MVC识别MetaDataType属性,但其他项目则没有。验证之前,您需要手动注册的元数据类:

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

这篇关于验证的DataAnnotations与Validator类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆