2010-08-29 97 views
2

我在我的模型元数据类以下属性:ASP.Net MVC 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)与新的正则表达式,它完美匹配。

我在做什么错?

回答

1

这是因为正则表达式适用于字符串,而不适用于DateTime属性。如果用户输入的无效字符串无法从模型联编程序中解析为DateTime实例,则会在执行正则表达式模式之前添加通用错误消息。

你有几个可能的原因:在资源文件

    1. Customize the error message编写自定义的模型绑定
    2. 使用的字符串属性(我感到内疚,提出这项:-))
  • +0

    aha,@Darin它将'DateTime'转换为'String',并没有给它'MM/dd/yyyy'谢谢亲爱的!我将开发新的'ValidationAttribute',因为在这个领域还需要一些其他的验证。 – TheVillageIdiot 2010-08-29 11:36:04

    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在应用程序启动注册客户端验证的正则表达式addapter像这样:

    DataAnnotationsModelValidatorProvider.RegisterAdapter(
          typeof(DateFormatValidatorAttribute), 
           typeof(RegularExpressionAttributeAdapter)); 
    

    现在你有内建MVC定期扩展验证器客户端,并保留DateTime作为您的财产类型