使用数据注释将十进制值validation为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; }
我想validation用户输入的小数位数不超过2位。 所以我想拥有
有效值 :12,12.3,12.34
无效值 :12.,12.345
有没有办法用数据注释validation这一点?
您可以使用RegularExpression属性,其正则表达式符合您的条件。 这里有一大堆表达涉及数字,我相信一个人会满足这个要求。 这是链接 。
这将让你开始,虽然它可能没有你想要的包容性(需要至少一个数字领先小数点):
[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Invalid price")]
请注意,很难发出精确的错误消息,因为您不知道正则表达式的哪个部分无法匹配(例如,字符串“z.22”具有正确的小数位数,但不是有效价格)。
[RegularExpression(@"^\d+.\d{0,2}$",ErrorMessage = "Price can't have more than 2 decimal places")] public decimal Price { get; set; }
这将满足0到2个小数位,或者根本不需要。
[RegularExpression(@"^\d+(\.\d)?$", ErrorMessage = "It cannot have more than one decimal point value")] [Range( 0.1,100)] public double xyz{get;set;}
它最适合我一个十进制值
您还可以创建自己的Decimalvalidation属性,inheritance自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()中启用客户端validation:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DecimalAttribute), typeof(RegularExpressionAttributeAdapter));
您可以使用正则表达式进行此validation,并将其应用于RegularExpression属性。
我有与OP相同的场景,但提供的答案并未提供适用于以下所有情况的解决方案:
12, 12.3 and 12.34
为此,我们使用以下正则表达式:
[RegularExpression(@"^\d+(.\d{1,2})?$")]
与mattytommo相似。 你需要逃避’。’ – 否则将接受任何角色
[RegularExpression(@"^\d+(\.\d{1,2})?$")]