我有以下代码工作
[Required(ErrorMessage = "Price is required.")]
[Range(typeof(Decimal), "1", "9999", ErrorMessage = "Price xx.xx")]
public decimal? productPrice { get; set; }
当页面提交时
价格 = EMPTY 字段错误消息是“需要价格。”。
价格 = 超过 9999 错误信息是“价格 xx.xx”。
但是,当我输入“aaaa”时,错误消息是
“字段 productPrice 必须是一个数字。”
如果输入不正确,如何更改消息?
比如:“价格必须是 1-9999 之间的小数/数字。
---- 更新:----
下面的代码与
NULL,不是十进制,在范围之间,但不适用于“.1”。
[Required(ErrorMessage = "Price is required.")]
[RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "Price must be a Numbers only.")]
[Range(typeof(Decimal), "1", "9999", ErrorMessage = "Price must be a decimal/number between {1} and {2}.")]
public decimal? productPrice { get; set; }
最佳答案
您可以尝试使用正则表达式:
[RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "{0} must be a Number.")]
您还可以尝试数据注释扩展:
http://dataannotationsextensions.org/Home/Wiki
或者编写自己的实现,如下所示:
https://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions/DigitsAttribute.cs
更新
使用正则表达式(匹配 $9,999.99 | $0.70 | .1)
[RegularExpression(@"^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$", ErrorMessage = "{0} must be a Number.")]
或者使用 Range 对 @Martin 建议稍加修改(实际上是一个更好的解决方案):
[Range(typeof(Decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]
关于asp.net - MVC 4 - DataAnnotations - 类型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12164728/