[英]Custom Validation Message, language specific
我有一個看起來像這樣的模型:
[LocalizedRegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", "RedesignEmailValidationError")]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "Emails mismatch!")]
public string EmailConfirm { get; set; }
問題是錯誤消息未本地化。 處理此問題的最佳方法是什么?
PS:我收到的語言特定文本需要在模型中的此表格上顯示; 理想情況下,我想使用那里提供的文字。
您需要使用ErrorMessageResourceName和ErrorMessageResourceType
應該是這樣的:
[Compare("EmailAddress", ErrorMessageResourceName = "ConfirmEmailErrorMessage", ErrorMessageResourceType=typeof(your_resource_type)]
public string EmailConfirm { get; set; }
另外,如果您不依賴默認資源提供程序,則必須自己實現。
喜歡:
[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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.