当我使用Validator.TryValidateObject验证不起作用 [英] Validation does not work when I use Validator.TryValidateObject

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

问题描述

的DataAnnotations不能与好友类的工作。下面code总是验证属实。为什么呢?

DataAnnotations does not work with buddy class. The following code always validate true. Why ?

变种的isValid = Validator.TryValidateObject(新客户(),上下文,结果,真);

var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);

和这里的哥们类。

public partial class Customer 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
}

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer 
{ 
    public class CustomerMetaData 
    { 
        [Required(ErrorMessage = "You must supply a name for a customer.")]        
        public string Name { get; set; } 
    } 
}

下面是另一个线程具有同样的问题,但没有答案。 <一href="http://stackoverflow.com/questions/2050161/validating-dataannotations-with-validator-class">link文字

Here is another thread with same question., but no answer. link text

推荐答案

我找到了答案在这里:<一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(Customer), typeof(CustomerMetadata)), typeof(Customer));

var isValid = Validator.TryValidateObject(new Customer(), context, results, true);

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

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