Visual Studio的默認ASP.NET MVC 2模板包含您需要的確切驗證屬性。從AccountModels.cs
文件粘貼:
[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("Password", "ConfirmPassword",
ErrorMessage = "The password and confirmation password do not match.")]
class NewUser {
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm password")]
public string ConfirmPassword { get; set; }
}
唯一的問題我可以用這個看到的是,當模型(在這種情況下類)的兩個屬性,是不相等的,它沒有將特定的屬性表示爲包含錯誤,就像它爲[Required]和<%= Html.ValidationMessageFor(m => m.Password1)%> – CodeMonkey 2010-03-15 22:04:18
@CodeMonkey所做的那樣,我明白了。雖然我不確定是否有一個優雅的解決方案,使其以另一種方式工作,使用模型綁定。畢竟,這在技術上是一個類級別的驗證。如果**必須**將錯誤添加到屬性中,則可能在綁定成爲最快解決方案(儘管不是最優雅的方案)後檢查控制器中的兩個值。 – 2010-03-15 22:45:52
在MVC 2版本中,Html.ValidationSummary幫助器方法現在可以顯示僅模型級錯誤 – murki 2010-03-25 20:14:00