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

Posted by Brandon Linton on Stack Overflow See other posts from Stack Overflow or by Brandon Linton
Published on 2010-04-07T20:32:44Z Indexed on 2010/04/07 20:33 UTC
Read the original article Hit count: 571

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!

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about validation