我在模型元数据类中有关注属性:

[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未验证。我已经使用相同的模式与新正则态度匹配了Entered Date(08/29/2010),并且它非常匹配。

我究竟做错了什么?

有帮助吗?

解决方案

那是因为正则施气适用于字符串,而不是 DateTime 特性。如果用户输入无效的字符串,该字符串无法解释为 DateTime 从模型活页夹中的实例将在将正则态度模式执行之前添加通用错误消息。

您有几种可能性:

  1. 自定义错误消息 在资源文件中
  2. 编写自定义模型活页夹
  3. 使用字符串属性(我为提出这个罪而感到内gui :-))

其他提示

实际上,还有另一个解决方法。您可以简单地将genularexpressionAttribute子属于

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上,应用程序开始注册客户端验证的gromularexpression indsapter这样:

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

现在,您可以拥有Build-In-In MVC常规外来验证器客户端,并将DateTime作为您的属性类型

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top