自定义验证消息,特定于语言

本文关键字:语言 于语言 验证 消息 自定义 | 更新日期: 2023-09-27 18:27:15

我有一个看起来像这样的模型:

[LocalizedRegularExpression(@"^['w-'.]+@(['w-]+'.)+['w-]{2,4}$", "RedesignEmailValidationError")]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "Emails mismatch!")]
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; }

您需要使用ErrorMessageResourceName和ErrorMessageResourceType

应该是这样的:

[Compare("EmailAddress", ErrorMessageResourceName = "ConfirmEmailErrorMessage", ErrorMessageResourceType=typeof(your_resource_type)]
public string EmailConfirm { get; set; }