2010-04-07 50 views
2

我們使用xVal和標準DataAnnotationsValidationRunner描述了here來收集ASP.NET MVC中我們的域對象和視圖模型的驗證錯誤。我想通過使用自定義DataAnnotation來讓驗證運行器識別何時兩個屬性不匹配。如何使用自定義ValidationAttribute來確保兩個屬性匹配?

現在我被迫做了亞軍之外,這種方式:

if (!(model.FieldOne == model.FieldTwo)) 
    errors.Add(new ErrorInfo("FieldTwo", "FieldOne must match FieldTwo", model.FieldTwo)); 

我的問題是:可以在此使用屬性級別的驗證特性來完成,還是我被迫使用類級別的屬性(在這種情況下,我不得不修改跑步者......我的後續問題將是如何最好地檢索他們)。

謝謝!

更新:我終於想出瞭如何編寫對象查詢來實現所選答案中的建議;如果任何人都好奇,我將這個查詢的結果與標準驗證跑步者的結果連接起來。請注意,我將TypeId更改爲確認字段屬性。

var classErrorQuery = 
     from attribute in 
      instance.GetType().GetCustomAttributes(typeof (ValidationAttribute), false).Cast 
      <ValidationAttribute>() 
     where !attribute.IsValid(instance) 
     select new ErrorInfo(attribute.TypeId.ToString(), attribute.FormatErrorMessage(string.Empty), instance); 
+0

可能重複[編寫一個CompareTo DataAnnotation屬性](http://stackoverflow.com/questions/1607832/writing-a-compareto-dataannotation-attribute) – Sheridan 2014-07-20 21:58:14

回答

1

看到Writing a CompareTo DataAnnotation Attribute

,你也可以檢查MVC2的默認項目的AccountMOdel,有PropertiesMustMatchAttribute應用於ChangePasswordModel屬性來驗證的新密碼和ConfirmPassword匹配

+0

+1爲MVC2項目參考,有趣的是看看他們如何完成它。我認爲它使用了他們內置的DataAnnotations跑步者。任何想法如何使用xVal的對象查詢收集此錯誤? – 2010-04-07 21:04:04

+0

@moi_meme感謝您指引我走向正確的方向;我最終找出了註解跑步者的一部分,但你所引用的代碼最終成爲我解決我的問題所需的最後一部分。謝謝! – 2010-04-08 02:27:45

相關問題