验证十进制值2与数据的注解小数位? [英] Validate decimal value to 2 decimal places with data annotations?

查看:183
本文介绍了验证十进制值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?

推荐答案

您可以使用RegularEx pression属性,与您的条件匹配一个正则表达式。这里有前pressions涉及的数字,我相信人会符合该法案的一大堆:
<一href=\"http://regexlib.com/DisplayPatterns.aspx?cattabindex=2&categoryId=3\">http://regexlib.com/DisplayPatterns.aspx?cattabindex=2&categoryId=3

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: http://regexlib.com/DisplayPatterns.aspx?cattabindex=2&categoryId=3

这将让你开始,虽然它可能不会像你想的包容性(至少需要一个数字导致小数点):

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"]

请注意,这是很难发出precise错误消息,因为你不知道正则表达式的一部分眼福(字符串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天全站免登陆