本地化 DataAnnotations 自定义验证属性
我目前正在开发一个 MVC 2 应用程序,该应用程序必须将所有内容都本地化为 n 种语言(目前有 2 种,顺便说一句,没有一种是英语)。我使用 DataAnnotations 验证我的模型类,但是当我想验证 DateTime 字段时,发现 DataTypeAttribute 始终返回 true,无论它是否是有效日期(这是因为当我输入随机字符串“foo”时,IsValid( )方法检查“01/01/0001”,不知道为什么)。
决定编写我自己的验证器来扩展 ValidationAtribute 类:
public class DateTimeAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
DateTime result;
if (value.ToString().Equals("01/01/0001 0:00:00"))
{
return false;
}
return DateTime.TryParse(value.ToString(), out result);
}
}
现在它会检查何时有效,何时无效,但是当我尝试本地化它时,我的问题就开始了:
[Required(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_Required")]
[CustomValidation.DateTime(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_DataType")]
public DateTime INS_DATA { get; set; }
如果我在字段中没有放置任何内容,我会得到本地化的 MSG(MSG 是我的资源) class) 的 key=INS_DATA_Required 但如果我输入格式错误的日期,我会收到“The value 'foo' is not valid for INS_DATA”默认消息,而不是本地化的 MSG。
我缺少什么?
I'm currently working in an MVC 2 app which has to have everything localized in n-languages (currently 2, none of them english btw). I validate my model classes with DataAnnotations but when I wanted to validate a DateTime field found out that the DataTypeAttribute returns always true, no matter it was a valid date or not (that's because when I enter a random string "foo", the IsValid() method checks against "01/01/0001 ", dont know why).
Decided to write my own validator extending ValidationAtribute class:
public class DateTimeAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
DateTime result;
if (value.ToString().Equals("01/01/0001 0:00:00"))
{
return false;
}
return DateTime.TryParse(value.ToString(), out result);
}
}
Now it checks OK when is valid and when it's not, but my problem starts when I try to localize it:
[Required(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_Required")]
[CustomValidation.DateTime(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_DataType")]
public DateTime INS_DATA { get; set; }
If I put nothing in the field I get a localized MSG (MSG being my resource class) for the key=INS_DATA_Required but if I put a bad-formatted date I get the "The value 'foo' is not valid for INS_DATA" default message and not the localized MSG.
What am I misssing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能是您的 ToString() 使用“本地化”格式,因此您的硬编码字符串将不匹配。
尝试将“if”条件替换为:
It could be that your ToString() is using a 'localized' format so your hard coded string will not match.
try replacing your "if" condition with: