使用数据注释覆盖默认的双重错误消息
在我的视图模型中,我有一个非常简单的成员,
[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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在根据正则表达式验证字段之前,将对其进行验证以确保其类型正确。由于“abc”无法转换为双精度型,因此您会收到该错误消息。
您可以将
salary
设为字符串,然后在控制器中将其解析为双精度型,这将阻止转换并允许在输入无效值时显示正则表达式错误消息。否则,使用
Html.ValidationMessageFor
覆盖验证消息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正则表达式应该用于字符串类型,不会为双精度类型调用它,因为首先不可能将“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.