Ste*_*ven 19 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; }
Run Code Online (Sandbox Code Playgroud)
我想验证用户输入的小数位数不超过2位.所以我想拥有
有效值:12,12.3,12.34
无效值:12.,12.345
有没有办法用数据注释验证这一点?
jle*_*lew 26
您可以使用RegularExpression属性,其正则表达式符合您的条件.这里有一大堆表达涉及数字,我相信一个人会适合这个账单.这是链接.
这将让你开始,虽然它可能没有你想要的包容性(要求至少一个数字领先小数点):
[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Invalid price")]
Run Code Online (Sandbox Code Playgroud)
请注意,很难发出精确的错误消息,因为您不知道正则表达式的哪个部分无法匹配(例如,字符串"z.22"具有正确的小数位数,但不是有效价格).
Jon*_*han 18
[RegularExpression(@"^\d+.\d{0,2}$",ErrorMessage = "Price can't have more than 2 decimal places")]
public decimal Price { get; set; }
Run Code Online (Sandbox Code Playgroud)
这将满足0到2个小数位,或者根本不需要.
您还可以创建自己的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);
}
}
Run Code Online (Sandbox Code Playgroud)
并注册它以在Application_Start()中启用客户端验证:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DecimalAttribute), typeof(RegularExpressionAttributeAdapter));
Run Code Online (Sandbox Code Playgroud)