DataAnnotations 自动处理 int 造成了障碍
摘要:DataAnnotation 自动处理“int?”让我重新考虑使用它们。
也许我错过了一些东西和一个简单的修复,但我无法让 DataAnnotations 合作。我有一个带有自己的自定义验证属性的公共属性:
[MustBeNumeric(ErrorMessage = "Must be a number")]
public int? Weight { get; set; }
自定义验证属性的要点是快速检查输入是否为数字并显示适当的错误消息。问题是,当 DataAnnotations 尝试将字符串绑定到 int 时?自动不会验证并显示“值‘asdf’对于重量无效。”
在我的一生中,我无法让 DataAnnotations 停止处理它,这样我就可以在我的自定义属性中处理它。
这似乎是一个流行的场景(验证数字输入),我猜有一个简单的解决方案,但我没有在任何地方找到它。
Summary: DataAnnotation's automatic handling of an "int?" is making me rethink using them at all.
Maybe I'm missing something and an easy fix but I can't get DataAnnotations to cooperate. I have a public property with my own custom validation attribute:
[MustBeNumeric(ErrorMessage = "Must be a number")]
public int? Weight { get; set; }
The point of the custom validation attribute is do a quick check to see if the input is numeric and display an appropriate error message. The problem is that when DataAnnotations tries to bind a string to the int? is automatically doesn't validate and displays a "The value 'asdf' is not valid for Weight."
For the life of me I can't get DataAnnotations to stop handling that so I can take care of it in my custom attribute.
This seems like it would be a popular scenario (to validate that the input in numeric) and I'm guessing there's an easy solution but I didn't find it anywhere.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个解决方法(因为我不会真正称其为解决方案)。在 Web 应用程序的
App_GlobalResources
文件夹中添加Messages.resx
文件。在里面添加以下资源:在
Global.asax
的Application_Start
方法中添加以下内容:Here's a workaround (as I wouldn't really call this a solution). Add a
Messages.resx
file inside theApp_GlobalResources
folder of your web application. Add the following resource inside:In the
Application_Start
method ofGlobal.asax
add the following: