我們使用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);
可能重複[編寫一個CompareTo DataAnnotation屬性](http://stackoverflow.com/questions/1607832/writing-a-compareto-dataannotation-attribute) – Sheridan 2014-07-20 21:58:14