2010-08-29 100 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作爲您的財產類型