C# 使用数据注释将十进制值验证为 2 个小数位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9558549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:53:10  来源:igfitidea点击:

Validate decimal value to 2 decimal places with data annotations?

c#asp.netasp.net-mvcasp.net-mvc-3

提问by Steven

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; }

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

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

Valid values: 12, 12.3, 12.34

有效值:12、12.3、12.34

Invalid values: 12., 12.345

无效值:12., 12.345

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

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

采纳答案by jlew

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.

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

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

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).

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

回答by Ion Sapoval

You can make this validation by using a regular expression and apply it with RegularExpression attribute.

您可以使用正则表达式进行此验证并将其应用到 RegularExpression 属性。

回答by Gurarpan

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

It works for me upto one decimal value

它适用于我最多一位十进制值

回答by Jonathan

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

This will cater for 0 to 2 decimal places, or none at all.

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

回答by domenu

You can also create your own Decimal validation attribute, inheriting from RegularExpressionAttribute:

您还可以创建自己的 Decimal 验证属性,继承自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);
    }
 }

and register it to enable client-side validation in Application_Start():

并在 Application_Start() 中注册它以启用客户端验证:

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

回答by mattytommo

I had the same scenario as the OP, yet the answers provided don't give a solution that works for all of the following cases:

我有与 OP 相同的场景,但提供的答案并没有提供适用于以下所有情况的解决方案:

12, 12.3 and 12.34

12, 12.3 and 12.34

To do that, we use the following regular expression:

为此,我们使用以下正则表达式:

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

回答by mattytommo

Similar to mattytommo. You need to escape '.' - otherwise ANY character will be accepted

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

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