2010-01-12 145 views
30

我试图验证装饰有Validator class的数据注释的类。使用验证程序类验证DataAnnotations

当属性应用于同一个类时,它工作正常。但是当我尝试使用元数据类时,它不起作用。有什么我应该用Validator做的,所以它使用元数据类?下面是一些代码..

这个工程:

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

感谢。

+0

我不能System.ComponentModel.DataAnnotations(MVC 2.0) 我做得不对内找到ValidationContext? – Myster 2010-07-21 23:24:56

+0

@Myster检查项目中是否引用了System.ComponentModel.DataAnnotations.dll。 – Pablote 2010-07-24 02:33:16

+0

只需使用[gist](https://gist.github.com/JimmyBoh/b7c135820c18a06648a5)(扩展方法),你可以调用p.Validate() – 2017-05-05 03:02:39

回答

41

我找到了答案在这里:http://forums.silverlight.net/forums/p/149264/377212.aspx

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

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

就是这样! :) – Pablote 2010-03-22 01:52:25

+0

我扩大我对这个类似问题的答案:http://stackoverflow.com/questions/1755340/validate-data-using-dataannotations-with-wpf-entity-framework/2467387#2467387 – 2010-10-13 17:13:59

+0

“validateAllProperties”标志绊倒了我。值得记住的是在适当的地方设置! – Gusdor 2017-10-24 09:21:55

0

尝试将元数据类移入与Persona类相同的名称空间(如果它尚未存在)。我遇到了类似的问题,并将我的元数据类移动到L2S模型类为我工作的相同名称空间中。

+1

它没有工作,我也试过把元数据类在课堂内,但没有运气。 – Pablote 2010-02-11 14:05:37