如何在 Asp.Net MVC 中显示 DisplayFormat 属性的自定义错误消息?

发布于 2024-12-29 02:33:11 字数 601 浏览 3 评论 0原文

如何显示自定义错误消息

[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 无效。

How to show a custom error message for

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

The code in my model is following,

[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; }

In my View when I enter 201 in the date textbox I get the following error message. How do I modify the error message below.

The value '201' is not valid for DocumentIssueDate.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薄荷→糖丶微凉 2025-01-05 02:33:11

经过大量研究后,我没有运气。唯一的解决方案是使用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 匹配。

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

After a lot of research I had no luck. The only solution was to use RegularExpression.

Instead of using:

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

You can use:

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

The RegularExpression matches the date format dd/MM/yyyy.

regular still not test yes but you can search and edit if need

所谓喜欢 2025-01-05 02:33:11

尝试在此处查看答案。我认为 DisplayFormat 设计不是为了验证,这就是为什么你不能使用它检查输入的字符串是否有效。

Try see answers Here. I think DisplayFormat designed not for validation, that is why you can not use it to check if entered string is valid.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文