C# Validation ErrorMessage 在语言基础上发生了变化

C# Validation ErrorMessage changed on language base

我必须根据语言设置验证消息。正如你在下面看到的,我有这个英文版本。

        [Required(ErrorMessage = "Email field is required")]  
        [StringLength(254, MinimumLength = 7, ErrorMessage="Email should be between 7 and 254 characters")]
        [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage= "Please insert a correct email address")]
        public string Email { get; set; }

我查看了如何实现错误消息的本地化,但我发现的只是如何对资源文件进行本地化。我需要根据从 CMS(Sitecore) 数据库中获得的数据进行本地化。

为了将 Sitecore 数据映射到 C# 模型,我使用了 Glass Mapper。

如何实现?

实现此目的的一种方法是创建您自己的自定义属性并从其中的 Sitecore 获取数据。 您可以继承 RequiredAttribute 等现有属性并覆盖 FormatErrorMessage.

您可以为消息创建 sitecore 字典,并且您需要以这种方式实现新的 class

 using Sitecore.Globalization;
 using System.ComponentModel.DataAnnotations;
 using System.Runtime.CompilerServices;

 public class CustomRequiredAttribute : RequiredAttribute
{
    /// <summary>
    /// The _property name
    /// </summary>
    private string propertyName;

    /// <summary>
    /// Initializes a new instance of the <see cref="CustomRequiredAttribute"/> class.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    public CustomRequiredAttribute([CallerMemberName] string propertyName = null)
    {
        this.propertyName = propertyName;
    }

    /// <summary>
    /// Gets the name of the property.
    /// </summary>
    /// <value>
    /// The name of the property.
    /// </value>
    public string PropertyName
    {
        get { return this.propertyName; }
    }

    /// <summary>
    /// Applies formatting to an error message, based on the data field where the error occurred.
    /// </summary>
    /// <param name="name">The name to include in the formatted message.</param>
    /// <returns>
    /// An instance of the formatted error message.
    /// </returns>
    public override string FormatErrorMessage(string name)
    {
        return string.Format(this.GetErrorMessage(), name);
    }

    /// <summary>
    /// Gets the error message.
    /// </summary>
    /// <returns>Error message</returns>
    private string GetErrorMessage()
    {
        return Translate.Text(this.ErrorMessage);
    }
}

表单的模型如下所示:

 public class AddressViewModel
 {
   [CustomRequiredAttribute(ErrorMessage = "Shipping_FirstName_Required")]
    public string FirstName { get; set; }
 }