2013-08-27 42 views
0

標題說明了一切,但我會在這裏添加一些背景。直到最近,我一直使用MVC的已編寫CompareAttribute來比較兩個值,在這種情況下,密碼和其確認。它運行良好,除了此屬性不顯示顯示名稱,由所比較屬性的[Display(Name = "Name")]屬性設置。如何使用客戶端驗證創建自定義比較屬性?

這裏有比較的兩個屬性:

[Required] 
[Display(Name = "New Password")] 
public string New { get; set; } 

[Compare("New")] 
[Display(Name = "Confirm Password")] 
public string ConfirmPassword { get; set; } 

驗證消息內容如下:

'Confirm Password' and 'New' do not match. 

這工作,但它顯然不如它應該是。根據Display屬性的規定,New應爲New Password

我已經得到了這個工作,雖然不完全。下面的實現(出於某種原因)修復沒有得到物業的指定名稱的問題,但我不知道爲什麼:

public class CompareWithDisplayNameAttribute : CompareAttribute 
{ 
    public CompareWithDisplayNameAttribute(string otherProperty) 
     : base(otherProperty) 
    { 
    } 
} 

現在,即使這個工程,客戶端驗證不起作用。我收到的答案不外乎在我Global.asax使用這樣的事情

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter)) 

另一個問題,但是CompareAttributeAdapter實際上並不存在。

所以我在這裏。我的Display屬性被我的自定義CompareWithDisplayName屬性正確使用,但客戶端驗證完全丟失。

如何以最簡潔的方式使用此解決方案進行客戶端驗證?

回答

2

如果您希望自定義比較屬性與客戶端驗證一起使用,則需要實施IClientValidatable。這有GetValidationRules這是你可以做任何你想要的自定義驗證。

public class CompareWithDisplayNameAttribute : CompareAttribute, IClientValidatable 
{ 
    public CompareWithDisplayNameAttribute(string otherProperty) 
     : base(otherProperty) 
    { 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
     ModelMetadata metadata, ControllerContext context) 
    { 
     // Custom validation goes here. 
     yield return new ModelClientValidationRule(); 
    } 
} 
相關問題