C#验证错误消息在语言基础上更改
我必须根据语言设置验证消息。正如你所看到的,我有这个英文版C#验证错误消息在语言基础上更改,c#,asp.net-mvc-4,sitecore,sitecore8,C#,Asp.net Mvc 4,Sitecore,Sitecore8,我必须根据语言设置验证消息。正如你所看到的,我有这个英文版 [Required(ErrorMessage = "Email field is required")] [StringLength(254, MinimumLength = 7, ErrorMessage="Email should be between 7 and 254 characters")] [RegularExpression(@"^\w+([-+.']\w+)*@\w+
[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字典,并且需要以这种方式实现一个新类
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; }
}