2

我的模型元数据类中有以下属性:

[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)与新的正则表达式匹配,并且完美匹配。

我究竟做错了什么?

4

2 回答 2

4

实际上,还有另一种解决方法。您可以简单地将 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 正则表达式验证器客户端并将 DateTime 作为您的属性类型

于 2010-11-24T15:31:13.620 回答
2

那是因为正则表达式适用于字符串而不是DateTime属性。如果用户输入了一个无法DateTime从模型绑定器解析为实例的无效字符串,它将在您的正则表达式模式执行之前添加一条通用错误消息。

你有几种可能性:

  1. 自定义资源文件中的错误消息
  2. 编写自定义模型绑定器
  3. 使用字符串属性(我为提出这个感到内疚:-))
于 2010-08-29T11:19:56.983 回答