我在Model Metadata类中有以下属性:
[Required(ErrorMessage = "Spent On is required")]
[RegularExpression(@"[0-1][0-9]/[0-3][0-9]/20[12][0-9]",
ErrorMessage = "Please enter date in mm/dd/yyyy format")]
[DataType(DataType.Date)]
[DisplayName("Spent On")]
public DateTime SpentOn { get; set; }
但是每当我调用ModelState.IsValid
时,它总是返回false,因为正则表达式没有验证。我已将输入的日期(08/29/2010)与使用相同模式的新正则表达相匹配,并且它完全匹配。
我做错了什么?
答案 0 :(得分:4)
Actualy还有另一种解决方法。您可以简单地继承RegularExpressionAttribute
public class DateFormatValidatorAttribute : RegularExpressionAttribute {
public DateFormatValidatorAttribute()
: base(@"[0-1][0-9]/[0-3][0-9]/20[12][0-9]")
{
ErrorMessage = "Please enter date in mm/dd/yyyy format";
}
public override bool IsValid(object value) {
return true;
}
}
应用程序启动时的Global.asax.cs中的注册了用于客户端验证的RegularExpression addapter,如下所示:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(DateFormatValidatorAttribute),
typeof(RegularExpressionAttributeAdapter));
现在您可以拥有内置MVC常规exression验证器客户端并将DateTime保留为您的属性类型
答案 1 :(得分:2)
这是因为正则表达式适用于字符串而不适用于DateTime
属性。如果用户输入的无效字符串无法从模型绑定器解析为DateTime
实例,则会在执行正则表达式模式之前添加一般错误消息。
您有几种可能性: