2012-03-04 93 views
15

我有这在我的视图模型:使用数据注释将小数点值验证为2位小数?

[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位小数。所以我想有

有效值:12,12.3,12.34

无效值:12,12.345

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

回答

19

你可以使用正则表达式的属性,与您的条件匹配一个正则表达式。这里有一大堆涉及数字的表达,我相信一个人会适合这个账单。这里是link

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

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

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

+1

对于带有句点(。)以外的小数点分隔符的语言,例如,逗号(14,6),因为RegularExpression将十进制转换为使用当前文化的字符串。 – jahav 2015-06-01 15:24:43

+0

'^ \ d *(\。|,|(\。\ d {1,2})|(,\ d {1,2}))?$'同时使用句点和逗号,在点之前的前面的数字或在该点之后的后面的数字。 – helrich 2016-03-04 13:21:10

+0

出于某种原因,给定正则表达式允许我插入多个小数点,例如:1.22.3.44 – Storm 2016-04-06 06:44:52

2

您可以通过使用正则表达式使这个验证,并与正则表达式属性应用它。

4
[RegularExpression(@"^\d+(\.\d)?$", ErrorMessage = "It cannot have more than one decimal point value")] 
[Range(0.1,100)] 
public double xyz{get;set;}   

它为我的作品高达一个十进制值

18
[RegularExpression(@"^\d+.\d{0,2}$",ErrorMessage = "Price can't have more than 2 decimal places")] 
public decimal Price { get; set; } 

这将满足0至2位小数,或根本没有。

+0

您可能想要转义'。' (这意味着“任何字符”,如果没有转义)给予^ \ d + \。\ d {0,5} $ – Appetere 2012-07-27 10:32:11

+2

糟糕,意思是^ \ d + \。?\ d {0,5} $与'?'只允许0或1次重​​复。 – Appetere 2012-07-27 10:41:25

+0

这实际上并不允许一个没有小数位的值,即'10',**但是**,它不允许有一个小数点:'10。 – mattytommo 2015-04-21 10:41:00

4

您也可以创建自己的十进制验证属性,从RegularExpressionAttribute继承:

public class DecimalAttribute : RegularExpressionAttribute 
{ 
    public int DecimalPlaces { get; set; } 
    public DecimalAttribute(int decimalPlaces) 
     : base(string.Format(@"^\d*\.?\d{{0,{0}}}$", decimalPlaces)) 
    { 
     DecimalPlaces = decimalPlaces; 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     return string.Format("This number can have maximum {0} decimal places", DecimalPlaces); 
    } 
} 

并注册它启用的Application_Start)客户端验证(:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DecimalAttribute), typeof(RegularExpressionAttributeAdapter)); 
0

我有同样的方案为OP,但提供不给,对所有的下列情况下有效的解决方案的答案:

12, 12.3 and 12.34

为了做到这一点,我们用下面的正则表达式:

[RegularExpression(@"^\d+(.\d{1,2})?$")] 
0

类似mattytommo。你需要逃避'。' - 否则将接受任何字符

[RegularExpression(@"^\d+(\.\d{1,2})?$")]