使用 Validator 类验证 DataAnnotations [英] Validating DataAnnotations with Validator class

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

问题描述

我正在尝试使用 验证器类.

当属性应用于同一个类时它工作正常.但是当我尝试使用元数据类时它不起作用.我应该对 Validator 做些什么以便它使用元数据类?这是一些代码..

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

这是我验证实例的方式:

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

谢谢.

推荐答案

我在这里找到了答案: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);

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

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