2010-03-15 32 views
6

我剛剛開始使用ASP.NET MVC 2,並使用驗證功能。如何使用ASP.NET MVC 2驗證兩個屬性

比方說,我有2個屬性:

  • 密碼1
  • 密碼2

我想要求他們都填寫,並要求這兩個是模型之前相同已驗證。

我有一個叫「NewUser」的簡單類。

我該如何實施?我已閱讀了有關ValidationAttribute,並瞭解這一點。但我不明白我將如何使用它來實現將兩個或更多屬性與eathother進行比較的驗證。

在此先感謝!

問題的以下溶液

當這個被施加到一個應用,並且所述模型綁定器運行模式的驗證,然後有一個問題:

如果屬性級別驗證屬性包含錯誤,那麼級別驗證屬性的是不是驗證。到目前爲止,我還沒有找到解決這個問題的方法。

如果您有解決此問題的方法,請分享您的經驗。非常感謝!

回答

7

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; } 
} 
+1

唯一的問題我可以用這個看到的是,當模型(在這種情況下類)的兩個屬性,是不相等的,它沒有將特定的屬性表示爲包含錯誤,就像它爲[Required]和<%= Html.ValidationMessageFor(m => m.Password1)%> – CodeMonkey 2010-03-15 22:04:18

+0

@CodeMonkey所做的那樣,我明白了。雖然我不確定是否有一個優雅的解決方案,使其以另一種方式工作,使用模型綁定。畢竟,這在技術上是一個類級別的驗證。如果**必須**將錯誤添加到屬性中,則可能在綁定成爲最快解決方案(儘管不是最優雅的方案)後檢查控制器中的兩個值。 – 2010-03-15 22:45:52

+0

在MVC 2版本中,Html.ValidationSummary幫助器方法現在可以顯示僅模型級錯誤 – murki 2010-03-25 20:14:00