C# 是否使用数据批注将十进制值验证为小数点后2位?
我的视图模型中有以下内容:C# 是否使用数据批注将十进制值验证为小数点后2位?,c#,asp.net,asp.net-mvc,asp.net-mvc-3,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 3,我的视图模型中有以下内容: [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
[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
有没有一种方法可以通过数据注释来验证这一点?您可以通过使用正则表达式并将其应用于RegularExpression属性来进行验证。您可以使用RegularExpression属性,并使用与您的条件相匹配的正则表达式。这里有一大堆涉及数字的表达,我相信其中一个会符合要求。这是你的电话号码 这将帮助您开始,尽管它可能没有您想要的那么全面(要求小数点前至少有一位数字): 请注意,很难发出准确的错误消息,因为您不知道正则表达式的哪个部分不匹配(例如,字符串“z.22”的小数位数正确,但不是有效的价格) 对于我来说,它最多可以工作一个十进制值
[RegularExpression(@"^\d+.\d{0,2}$",ErrorMessage = "Price can't have more than 2 decimal places")]
public decimal Price { get; set; }
这将满足0到2位小数的要求,或者根本没有小数。您还可以创建自己的小数验证属性,继承自: 并将其注册以在应用程序_Start()中启用客户端验证:
我的场景与OP相同,但提供的答案并不能提供适用于以下所有情况的解决方案:
12、12.3和12.34
为此,我们使用以下正则表达式:
[RegularExpression(@"^\d+(.\d{1,2})?$")]
类似于MattyMo。您需要转义“”-否则将接受任何字符
[RegularExpression(@"^\d+(\.\d{1,2})?$")]
要使其适用于使用小数分隔符而不是句点(.)的语言,请执行以下操作:
使用系统;
使用System.ComponentModel.DataAnnotations;
利用制度全球化;
///
///十进制精度验证器数据注释。
///
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
公共密封类DecimalPrecisionAttribute:ValidationAttribute
{
专用只读单元的精度;
公共决策精度属性(uint决策精度)
{
_decimalPrecision=decimalPrecision;
}
公共覆盖布尔值有效(对象值)
{
返回值为null | |(值为十进制d&&HasPrecision(d,_decimalPrecision));
}
专用静态布尔HasPrecision(十进制值,uint精度)
{
字符串valueStr=value.ToString(CultureInfo.InvariantCulture);
int indexOfDot=valueStr.IndexOf('.');
如果(indexOfDot==-1)
{
返回true;
}
返回值str.Length-indexOfDot-1您可能希望转义“.”(如果未转义,则表示“任何字符”),以给出^\d+\。\d{0,5}$Oops,对不起,意思是^\d+\。?\d{0,5}带“?”的$只允许0或1次重复。这实际上不允许值不带小数点,例如10
,但是,它不允许带点的小数点:10。
这不适用于带小数点分隔符(句点除外)的语言,例如逗号(14,6),因为RegularExpression使用当前区域性将十进制转换为字符串。^\d*(\.\124;,|(\.\ d{1,2})|(,\d{1,2}))怎么样?$
既有句点又有逗号,也不允许在点之前有前导数字,也不允许在点之后有数字。出于某种原因,给定的正则表达式允许我插入多个小数点,例如:1.22.3。44@jahav,检查franck duhaupas的答案,解决您的问题!
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);
}
}
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DecimalAttribute), typeof(RegularExpressionAttributeAdapter));
[RegularExpression(@"^\d+(.\d{1,2})?$")]
[RegularExpression(@"^\d+(\.\d{1,2})?$")]