title: How can I use a custom ValidationAttribute to ensure two properties match?
body: <p>We're using xVal and the standard <code>DataAnnotationsValidationRunner</code> described <a href="http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/" rel="nofollow noreferrer">here</a> 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.</p>
  
  <p>Right now I'm forced into doing it outside of the runner, this way:</p>
  
  <pre><code>if (!(model.FieldOne == model.FieldTwo))
      errors.Add(new ErrorInfo("FieldTwo", "FieldOne must match FieldTwo", model.FieldTwo));
  </code></pre>
  
  <p>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).</p>
  
  <p>Thanks!</p>
  
  <p><strong>UPDATE:</strong>  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.</p>
  
  <pre><code>var classErrorQuery =
        from attribute in
            instance.GetType().GetCustomAttributes(typeof (ValidationAttribute), false).Cast
            &lt;ValidationAttribute&gt;()
        where !attribute.IsValid(instance)
        select new ErrorInfo(attribute.TypeId.ToString(), attribute.FormatErrorMessage(string.Empty), instance);
  </code></pre>