在开发国际化应用程序时,经常需要根据用户的语言和地理位置显示相应的错误消息。本文将介绍如何在ASP.NETMVC应用程序中实现这一功能。将使用Visual Studio 2013创建一个基础的MVC应用程序,并添加自定义验证代码。
首先,打开Visual Studio 2013 IDE并创建一个新的ASP.NET Web应用程序。选择MVC模板,然后点击OK,无需更改其他选项。这将为提供一个现成的小应用程序,可以在此基础上添加代码。使用了注册页面来创建自定义验证。
接下来,将创建两个自定义验证器,一个用于自定义必填验证,另一个用于自定义不允许特殊字符验证。
RequiredValidation类将继承自ValidationAttribute基类。将重写IsValid函数,以创建自定义验证。这个函数接受两个参数,第一个是ValidationContext,它将提供要验证的属性的显示名称;第二个是待验证的值。
public class RequiredValidationAttribute : ValidationAttribute
{
public static string ValidationResourceFile = "/App_Data/ValidationMessages.xml";
public RequiredValidationAttribute() : base("{0}")
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null || value.ToString().Trim() == "")
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName) +
" - " + Models.Helpers.ValidationHelper.GetResourceString(ValidationResourceFile,
"Required",
"EN",
"XY"));
}
return ValidationResult.Success;
}
}
CharNotAllowed类将用于不允许特定的特殊字符。不允许的字符将通过数据注解传递,并存储在_invalidChars变量中。
public class CharNotAllowedAttribute : ValidationAttribute
{
public static string ValidationResourceFile = "/App_Data/ValidationMessages.xml";
private readonly string _invalidChars;
public CharNotAllowedAttribute(string invalidChars) : base("{0}")
{
_invalidChars = invalidChars;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
for (int i = 0; i < _invalidChars.Length; i++)
{
if (value.ToString().Contains(_invalidChars[i]))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName) +
" - " +
Models.Helpers.ValidationHelper.GetResourceString(ValidationResourceFile,
"Invalid_Chars",
"EN",
"XY"));
}
}
}
return ValidationResult.Success;
}
}
ValidationHelper类将用于根据提供的键、语言和状态获取错误消息。
public class ValidationHelper
{
public static string GetResourceString(string resourceFile, string resourceKey, string lang, string state)
{
string retValue = string.Empty;
XDocument xDoc = XDocument.Load(resourceFile);
var MessageResource = from m in xDoc.Descendants("ValidationMessage")
.Where(r => (string)r.Attribute("ID") == resourceKey)
select m;
var Msg = from m in MessageResource.Descendants("Expression")
.Where(r => (string)r.Element("lang").Value == lang &&
(bool)r.Element("state").Value.Contains(state) == true)
select m.Parent;
foreach (XElement element in Msg.Descendants("Message"))
{
retValue = element.Value.ToString();
}
return retValue;
}
}
public class RegisterViewModel
{
[RequiredValidation]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[RequiredValidation]
[CharNotAllowed("@#")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}