我的模型看起来像这样:
[LocalizedRegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", "RedesignEmailValidationError")]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "Emails mismatch!")]
public string EmailConfirm { get; set; }
问题是错误消息未本地化。处理这个问题的最佳方法是什么?
PS:我收到模型中需要在此表单上的特定语言文本;理想情况下,我想使用那里提供的文本。
答案 0 :(得分:2)
您需要使用ErrorMessageResourceName和ErrorMessageResourceType
应该是这样的:
[Compare("EmailAddress", ErrorMessageResourceName = "ConfirmEmailErrorMessage", ErrorMessageResourceType=typeof(your_resource_type)]
public string EmailConfirm { get; set; }
答案 1 :(得分: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; }