使用数据注释将十进制值验证为 2 个小数位? [英] Validate decimal value to 2 decimal places with data annotations?

查看:17
本文介绍了使用数据注释将十进制值验证为 2 个小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图模型中有这个:

I have this in my view model:

[Required(ErrorMessage = "Price is required")]
[Range(0.01, 999999999, ErrorMessage = "Price must be greater than 0.00")]
[DisplayName("Price ($)")]
public decimal Price { get; set; }

我想验证用户输入的小数位不超过 2 位.所以我想要

I'd like to validate that the user doesn't enter more than 2 decimal places. So I'd like to have

有效值:12、12.3、12.34

Valid values: 12, 12.3, 12.34

无效值:12., 12.345

Invalid values: 12., 12.345

有没有办法用数据注释来验证这一点?

Is there a way to validate this with a data annotation?

推荐答案

您可以使用与您的条件匹配的正则表达式的 RegularExpression 属性.这里有一大堆涉及数字的表达方式,我相信其中一个会符合要求.这是链接.

You could use the RegularExpression attribute, with a regex that matches your criteria. There are a whole bunch of expressions here that involve numbers, I'm sure one will fit the bill. Here is the link.

这会让你开始,虽然它可能没有你想要的那么包容(需要至少一位数字前导小数点):

This will get you started, though it may not be as inclusive as you want (requires at least one digit leading the decimal point):

[RegularExpression(@"d+(.d{1,2})?", ErrorMessage = "Invalid price")]

请注意,很难发出精确的错误消息,因为您不知道正则表达式的哪一部分匹配失败(例如,字符串z.22"具有正确的小数位数,但不是一个有效的价格).

Note that it is difficult to emit a precise error message because you don't know which part of the regex failed to match (the string "z.22" has the correct number of decimal places, for example, but is not a valid price).

这篇关于使用数据注释将十进制值验证为 2 个小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆