views:

191

answers:

1

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  A: 

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

moi_meme
+1 for the MVC2 project reference, interesting to see how they accomplish it. I assume it's using their built-in DataAnnotations runner though. Any idea on how to collect this error with an object query for xVal?
Brandon Linton
@moi_meme thanks for pointing me in the right direction; I ended up figuring out the annotation runner piece but the code you reference ended up being the last piece I needed to solve my problem. Thanks!
Brandon Linton