DataAnnotations 自动处理 int 造成了障碍

发布于 2024-09-04 11:02:13 字数 453 浏览 4 评论 0原文

摘要: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 技术交流群。

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

发布评论

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

评论(1

心安伴我暖 2024-09-11 11:02:13

这是一个解决方法(因为我不会真正称其为解决方案)。在 Web 应用程序的 App_GlobalResources 文件夹中添加 Messages.resx 文件。在里面添加以下资源:

Key: PropertyValueInvalid
Value: {0} Must be a number

Global.asaxApplication_Start方法中添加以下内容:

DefaultModelBinder.ResourceClassKey = "Messages";

Here's a workaround (as I wouldn't really call this a solution). Add a Messages.resx file inside the App_GlobalResources folder of your web application. Add the following resource inside:

Key: PropertyValueInvalid
Value: {0} Must be a number

In the Application_Start method of Global.asax add the following:

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