首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#验证ErrorMessage在语言基础上更改

C#验证ErrorMessage在语言基础上更改
EN

Stack Overflow用户
提问于 2016-05-30 15:14:13
回答 2查看 1.3K关注 0票数 3

我必须根据语言设置验证消息。如你所见,我有这个英文的。

代码语言:javascript
复制
        [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。

如何实现这一点?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-30 16:41:43

您可以为消息编写sitecore字典,并且需要以这种方式实现一个新的类。

代码语言:javascript
复制
 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);
    }
}

该表单的模型如下:

代码语言:javascript
复制
 public class AddressViewModel
 {
   [CustomRequiredAttribute(ErrorMessage = "Shipping_FirstName_Required")]
    public string FirstName { get; set; }
 }
票数 3
EN

Stack Overflow用户

发布于 2016-05-30 15:24:28

这样做的一种方法是创建您自己的自定义属性,并从其中的Sitecore获取您的数据。您可以从现有属性(如RequiredAttribute )继承并重写FormatErrorMessage

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37528982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档