我们正在使用xVal和标准的DataAnnotationsValidationRunner
描述here来收集ASP.NET MVC中的域对象和视图模型的验证错误。我希望有一种方法让验证运行器通过使用自定义DataAnnotations来识别两个属性不匹配。
现在我被迫在跑步者之外做这件事:
if (!(model.FieldOne == model.FieldTwo))
errors.Add(new ErrorInfo("FieldTwo", "FieldOne must match FieldTwo", model.FieldTwo));
我的问题是:这可以使用属性级验证属性来完成,还是我被迫使用类级属性(在这种情况下,我必须修改运行程序......我的后续问题会在这种情况下,如何最好地检索它们。)
谢谢!
更新:我终于想出了如何编写对象查询来实现所选答案中的建议;如果有人好奇,我会将此查询的结果与标准验证运行程序的结果联系起来。请注意,我将TypeId更改为confirm字段属性。
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 :(得分:1)
请参阅Writing a CompareTo DataAnnotation Attribute
并且您还可以在MVC2的默认项目中检查AccountMOdel,有一个属性PropertiesMustMatchAttribute应用于ChangePasswordModel以验证NewPassword和ConfirmPassword匹配