使用数据注释覆盖默认的双重错误消息

发布于 2024-11-08 11:52:07 字数 335 浏览 0 评论 0原文

在我的视图模型中,我有一个非常简单的成员,

[RegularExpression(@"^[0-9\.]*$", 
   ErrorMessage = "The only value you can enter here is a number")]
public double salary{ get; set; }

但是当我将“abc”这样的值放入文本框中时,我收到此错误消息,

值“abc”对于工资无效。

这不是我定义的错误消息。是否存在某种无法用注释覆盖的默认行为?我必须编写自定义验证器吗?

In my view model I have this very simple member,

[RegularExpression(@"^[0-9\.]*$", 
   ErrorMessage = "The only value you can enter here is a number")]
public double salary{ get; set; }

but when I put a value like 'abc' into the textbox, I receive this error message,

The value 'abc' is not valid for salary.

which is not the error message I've defined. Is there some sort of default behavior that you can't overwrite with annotations? Do I have to write a custom validator?

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

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

发布评论

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

评论(2

魄砕の薆 2024-11-15 11:52:07

在根据正则表达式验证字段之前,将对其进行验证以确保其类型正确。由于“abc”无法转换为双精度型,因此您会收到该错误消息。

您可以将 salary 设为字符串,然后在控制器中将其解析为双精度型,这将阻止转换并允许在输入无效值时显示正则表达式错误消息。

否则,使用 Html.ValidationMessageFor 覆盖验证消息

@Html.ValidationMessageFor(m => m.salary, "The only value you can enter here is a number")

Before the field is validated against your regular expression, it is being validated to ensure that it is the correct type. Since 'abc' can't be converted to a double, you get that error message.

You could make salary a string and then parse it into a double in your controller, that will prevent the conversion and allow your Regex error message to be displayed when an invalid value is entered.

Otherwise, use Html.ValidationMessageFor to override the validation message

@Html.ValidationMessageFor(m => m.salary, "The only value you can enter here is a number")
灰色世界里的红玫瑰 2024-11-15 11:52:07

正则表达式应该用于字符串类型,不会为双精度类型调用它,因为首先不可能将“abc”分配给双精度类型。

RegularExpression should be used for string type, it will not be called for a double type since it is not possible to assign 'abc' to a double in the first place.

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