ASP.Net MVC 2模型验证正则表达式验证器失败

时间:2010-08-29 11:15:24

标签: asp.net-mvc-2 validation model-validation

我在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)与使用相同模式的新正则表达相匹配,并且它完全匹配。

我做错了什么?

2 个答案:

答案 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实例,则会在执行正则表达式模式之前添加一般错误消息。

您有几种可能性:

    资源文件中的
  1. Customize the error message
  2. 编写自定义模型绑定器
  3. 使用字符串属性(我对提出这个问题感到内疚: - ))