我目前正在使用MVC4数据注释来处理验证.我正在开发一个非常国际化的网站,因此我将所有文本保存在资源文件中.
我还想在资源文件中保留正则表达式以进行验证,这样我就可以使用相同的代码来检查,例如,Post Codes(UK)和Zip Codes(US),只需使用不同的RegEx(以及不同名称的资源等) ).
我有以下属性已经从资源文件中提取错误消息.我怎样才能从资源文件中获取正则表达式?
[RegularExpression(@"^[\w]{1,2}[0-9]{1,2}[\w]?\s?[0-9]{1,2}[\w]{1,2}$", ErrorMessageResourceType = typeof(Resources.ValidationMessages), ErrorMessageResourceName = "validPostcode")]
Run Code Online (Sandbox Code Playgroud)
编辑(再次)
我现在在哪里
按照下面的答案和一些额外的搜索,我有以下内容:
在Global.asax.cs我添加了以下行,以确保调用客户端验证
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalisedAttribute), typeof(RegularExpressionAttributeAdapter));
Run Code Online (Sandbox Code Playgroud)
在我的模型中,我调用了属性扩展
[Localised(typeof(Resources.FormValidation), "postcodeRegEx", "postcodeMsg")]
Run Code Online (Sandbox Code Playgroud)
最后,本地化正则表达式验证的属性扩展
public class LocalisedAttribute : RegularExpressionAttribute
{
public LocalisedAttribute(Type resource, string regularExpression, string errorMessage)
: base(GetRegex(regularExpression))
{
ErrorMessageResourceType = resource;
ErrorMessageResourceName = errorMessage;
}
private static string GetRegex(string value)
{
return Resources.FormValidation.ResourceManager.GetString(value);
}
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,但只是我第一次在启动应用程序时使用它.
我将打开另一个问题来解决这个问题 - 它与原始请求没有直接关系,似乎与大多数人的实现没有关系,似乎并不特定于数据注释.
asp.net asp.net-mvc custom-attributes data-annotations asp.net-mvc-4