2014-10-20 177 views
0

語言,我有一個模型,它看起來是這樣的:自定義驗證消息,具體

[LocalizedRegularExpression(@"^[\w-\.][email protected]([\w-]+\.)+[\w-]{2,4}$", "RedesignEmailValidationError")] 
public string EmailAddress { get; set; } 

[Compare("EmailAddress", ErrorMessage = "Emails mismatch!")] 
public string EmailConfirm { get; set; } 

的問題是,該錯誤消息未本地化。處理這個問題的最佳方法是什麼? PS:我收到需要在模型中的此表單上的語言特定文本;理想情況下,我想使用那裏提供的文字。

回答

2

此外,如果你不依賴於默認的資源提供者,你必須自己實現它。

像:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)] 
public sealed class LocalizedDisplayNameAttribute : DisplayNameAttribute { 
    public LocalizedDisplayNameAttribute() { 
    } 

    public LocalizedDisplayNameAttribute(object context) { 
    Context = context; 
    } 

    public object Context { get; set; } 

    public override string DisplayName { 
    get { 
     // TODO: override based on CultureInfo.CurrentCulture and Context here 
     return "LocalizedAttributeName"; 
    } 
    } 
} 

[AttributeUsage(AttributeTargets.Property)] 
public class LocalizedCompareAttribute : CompareAttribute { 

    public object Context { get; set; } 

    public LocalizedCompareAttribute(string otherProperty) 
    : base(otherProperty) { 
    } 

    public override string FormatErrorMessage(string name) { 
    // TODO: override based on CultureInfo.CurrentCulture and Context here 
    string format = "Field '{0}' should have the same value as '{1}'."; 
    return string.Format(CultureInfo.CurrentCulture, format, name, OtherPropertyDisplayName);  
    } 
} 

用法:

[LocalizedCompare("EmailAddress", Context = "ResourceKey_EmailMismatch")] 
[LocalizedDisplayName("ResourceKey_Email")] 
public string EmailConfirm { get; set; } 
+0

我喜歡這種方法,謝謝! – RealityDysfunction 2014-10-20 16:43:45