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);
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
精彩评论