MVC2 поставляется с образцом «PropertiesMustMatchAttribute», который показывает, как заставить DataAnnotations работать для вас, и он должен работать как в .NET 3.5, так и в .NET 4.0. Этот пример кода выглядит следующим образом:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty
{
get;
private set;
}
public string OriginalProperty
{
get;
private set;
}
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
// ignore case for the following
object originalValue = properties.Find(OriginalProperty, true).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}
При использовании этого атрибута, а не поставить его на свойство вашей модели класса, вы положили его на сам класс:
[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public class ChangePasswordModel
{
public string NewPassword { get; set; }
public string ConfirmPassword { get; set; }
}
Когда «IsValid «получает вызов по вашему пользовательскому атрибуту, весь экземпляр модели передается ему, поэтому вы можете получить значения зависимых свойств таким образом. Вы можете легко следовать этому шаблону, чтобы создать еще более общий атрибут сравнения.
Я думаю, что для проверки класса, а не поля, необходимо применить некоторую проверку. – Jay