2014-02-21 52 views
0

我試圖執行StringLengthAttribute類以覆蓋FormatErrorMessage()方法。實現StringLengthAttribute類不工作

但是,添加新的標註StringLengthWithCustomErrorMessage的財產後,不顯眼的驗證是由HTML輸出丟失:

data-val-length="Error message"

我失去了一些東西?

public class StringLengthWithCustomErrorMessageAttribute : StringLengthAttribute 
{ 
    public StringLengthWithCustomErrorMessageAttribute(int maximumLength) 
     :base(maximumLength) 
    { 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     return string.Format("Value must be between {0} and {1} characters", MinimumLength, MaximumLength); 
    } 
} 
+0

爲什麼你就是不傳遞錯誤信息到'StringLengthAttribute'像'[StringLength(10,MinimumLength = 1, ErrorMessage =「值必須介於{2}和{1}個字符之間」)''? – Zabavsky

+0

這工作,謝謝。然而,我仍然很高興知道爲什麼我的嘗試沒有奏效 – Catalin

回答

0

您需要添加一個適配器,爲您的自定義屬性StringLengthWithCustomErrorMessageAttribute

protected void Application_Start() { 
    DataAnnotationsModelValidatorProvider 
    .RegisterAdapter(typeof(StringLengthWithCustomErrorMessageAttribute), 
    typeof(StringLengthAttributeAdapter)); 
}