How can I use a custom ValidationAttribute to ensure two properties match?

邮差的信 提交于 2019-12-11 00:14:04

问题


We're using xVal and the standard DataAnnotationsValidationRunner described here to collect validation errors from our domain objects and view models in ASP.NET MVC. I'd like to have a way to have that validation runner identify when two properties don't match through the use of custom DataAnnotations.

Right now I'm forced into doing it outside of the runner, this way:

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

My question is: can this be done using property-level validation attributes, or am I forced into using class-level attributes (in which case, I'd have to modify the runner...and my follow up question would be how best to retrieve them in that case).

Thanks!

UPDATE: I finally figured out how to write the object query to implement the suggestion in the selected answer; I concat the results of this query with the results of the standard validation runner, if anyone was curious. Note that I changed the TypeId to be the confirm field property.

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);

回答1:


see Writing a CompareTo DataAnnotation Attribute

and also you can check The AccountMOdel in the default project of MVC2, There is an attribute PropertiesMustMatchAttribute applied to the ChangePasswordModel to validate that the NewPassword and ConfirmPassword Match



来源:https://stackoverflow.com/questions/2595715/how-can-i-use-a-custom-validationattribute-to-ensure-two-properties-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!