+-

我必须根据语言设置验证消息.如您所见,波纹管我用的是英语.
[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字典,并且需要以这种方式实现新类
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; }
}
点击查看更多相关文章
转载注明原文:C#验证ErrorMessage已基于语言更改 - 乐贴网