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

时间:2022-03-29 16:31:01

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?

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

7 个解决方案

#1


22  

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”具有正确的小数位数,但不是有效价格)。

#2


18  

[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个小数位,或者根本不需要。

#3


4  

[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

它最适合我一个十进制值

#4


4  

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

#5


2  

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

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

#6


0  

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和12.34

To do that, we use the following regular expression:

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

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

#7


0  

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

与mattytommo相似。你需要逃避'。' - 否则将接受任何角色

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

#1


22  

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”具有正确的小数位数,但不是有效价格)。

#2


18  

[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个小数位,或者根本不需要。

#3


4  

[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

它最适合我一个十进制值

#4


4  

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

#5


2  

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

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

#6


0  

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和12.34

To do that, we use the following regular expression:

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

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

#7


0  

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

与mattytommo相似。你需要逃避'。' - 否则将接受任何角色

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