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);
object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).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”时,整个模型实例都会传递给它,以便您可以通过这种方式获取依赖属性值。您可以轻松地遵循此模式来创建日期比较属性,甚至更通用的比较属性。
Brad Wilson 在他的博客上有一个很好的例子展示了如何添加验证的客户端部分,但我不确定该示例是否适用于 .NET 3.5 和 .NET 4.0。