代码之家  ›  专栏  ›  技术社区  ›  TheVillageIdiot

ASP.Netmvc2模型验证Regex验证器失败

  •  2
  • TheVillageIdiot  · 技术社区  · 14 年前

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

    [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,因为regex没有验证。我已经使用相同的模式将输入的日期(08/29/2010)与新的regex进行了匹配,而且匹配得非常完美。

    我做错什么了?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Community Lee    7 年前

    这是因为regex应用于字符串而不是 DateTime 属性。如果用户输入了无法解析为 日期时间 实例,它将在regex模式执行之前添加一个通用错误消息。

    1. Customize the error message 在资源文件中
    2. 编写自定义模型活页夹
        2
  •  4
  •   TheVillageIdiot    14 年前

    实际上还有另一个解决方法。您可以简单地将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;
            }
    }
    

    在你的全球.asax.cs在应用程序启动时,注册RegularExpression addapter进行客户端验证,如下所示:

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

    现在您可以在MVC常规exression验证器客户端中进行构建,并将DateTime作为属性类型