【问题标题】:How to show a custom error message for DisplayFormat attribute In Asp.Net MVC?如何在 Asp.Net MVC 中显示 DisplayFormat 属性的自定义错误消息?
【发布时间】:2012-01-25 02:21:51
【问题描述】:

如何显示自定义错误消息

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]

我的模型中的代码如下,

[Display(Name = "When was that document issued?")]
[DataType(DataType.Date, ErrorMessageResourceName = "DocumentIssueDate_DataType",ErrorMessageResourceType = typeof(CustomErrorMessages))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
 public DateTime? DocumentIssueDate { get; set; }

在我的视图中,当我在日期文本框中输入 201 时,我收到以下错误消息。如何修改下面的错误信息。

值“201”对于 DocumentIssueDate 无效。

【问题讨论】:

  • 你对DocumentIssueDate_DataType有什么要求?
  • 资源文件 (.resx) 中的字符串消息。例如“日期必须输入为 dd/mm/yyyy(例如 31/01/1997)。”

标签: asp.net-mvc-3 data-annotations


【解决方案1】:

经过大量研究,我没有运气。唯一的解决方案是使用RegularExpression

而不是使用:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]

你可以使用:

[RegularExpression(@"^(3[01]|[12][0-9]|0[1-9])[-/](1[0-2]|0[1-9])[-/][0-9]{4}$", ErrorMessageResourceName = "Date Not Valid")]

RegularExpression 匹配日期格式dd/MM/yyyy

regular 仍然没有测试是,但您可以根据需要搜索和编辑

【讨论】:

    【解决方案2】:

    尝试查看答案Here. 我认为 DisplayFormat 不是为验证而设计的,这就是为什么您不能使用它来检查输入的字符串是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多