我们使用 xVal 和标准 DataAnnotationsValidationRunner 描述 这里 从 ASP.NET MVC 中的域对象和视图模型收集验证错误。我希望有一种方法可以让验证运行程序通过使用自定义数据注释来识别两个属性何时不匹配。

现在我被迫在跑步者之外这样做,这样:

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 属性

您还可以检查MVC2默认项目中的AccountMOdel,有一个属性PropertiesMustMatchAttribute应用于ChangePasswordModel来验证NewPassword和ConfirmPassword是否匹配

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top