2010-01-12 141 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