使用 MVC 和数据注释在客户端添加大于 0 的验证器的最佳方法是什么?
我希望能够仅在某个字段中的值大于 0 时才允许提交表单。我想也许 Mvc Range 属性将允许我仅输入 1 个值来表示仅大于测试,但是那里没有运气,因为它坚持最小值和最大值。
有什么想法可以实现这一点吗?
I'd like to be able to only allow a form to submit if the value in a certain field is greater than 0. I thought maybe the Mvc Range attribute would allow me to enter only 1 value to signify only a greater than test, but no luck there as it insists on Minimum AND Maximum values.
Any ideas how this can be achieved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法存储大于基础数据类型可以容纳的数字,因此 Range 属性需要最大值这一事实是一件非常好的事情。请记住,现实世界中不存在
∞
,因此以下内容应该有效:You can't store a number bigger than what your underlying data type could hold so that fact that the Range attribute requires a max value is a very good thing. Remember that
∞
doesn't exist in the real world, so the following should work:我发现这个答案旨在验证浮点数/双精度数的任何正值。事实证明,这些类型有一个有用的常量“Epsilon”
I found this answer looking to validate any positive value for a float/double. It turns out these types have a useful constant for 'Epsilon'
您可以像这样创建自己的验证器:
然后在模型中“包含”该文件并将其用作属性,如下所示:
我通常在下拉验证中使用它。请注意,因为它扩展了validationattribute,所以您可以使用参数自定义错误消息。
You can create your own validator like this:
Then "include" that file in your model and use it as an attribute like this:
I commonly use this on dropdown validation. Note that because it's extending validationattribute you can customize the error message with a parameter.
上面的验证器适用于整数。我将其扩展为使用小数:
The above validator works with integers. I extended this to work with a decimal: