我正在开发一个 asp.net mvc web 应用程序,我在 sql server Decimal(19,2)
中有一个具有以下数据类型的小数字段。现在我想检查用户是否只能输入 2 位数字,但他们可以添加数字,例如 10 、 20 (没有任何数字).. 但如果他们设置数字以检查是否有最多两位数。
现在我尝试了以下 RegularExpression,但没有一个效果很好:-
此 RegularExpression 将不允许用户输入不包含数字的数字:-
[RegularExpression(@"^\d+.\d{0,2}$", ErrorMessage = "Value can't have more than 2 decimal places")]
public Nullable<decimal> CostPrice { get; set; }
如果用户尝试输入数字,这个 RegularExpression 将引发错误:-
[RegularExpression(@"^(\d{0,2})$", ErrorMessage = "error Message")]
public Nullable<decimal> CostPrice { get; set; }
所以任何人都可以建议什么是最好的 RegularExpression,它强制用户输入最多 2 位数字,同时允许他们输入没有任何数字的数字?
最佳答案
描述
^(?!\s*[0-9]{0,2}\s*$).*$
此正则表达式将执行以下操作:
- 验证字符串最多由空格包围的 2 位数字
- 如果字符串最多包含 2 位数字,则表达式为假
- 如果字符串包含的数字超过 2 位,则表达式为真
- 如果字符串中包含任何字母,则表达式为真
实例
https://regex101.com/r/vQ1gW1/1
说明
NODE EXPLANATION
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0
or more times (matching the most amount
possible))
----------------------------------------------------------------------
[0-9]{0,2} any character of: '0' to '9' (between 0
and 2 times (matching the most amount
possible))
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0
or more times (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of
the string
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
关于c# - 在我的 asp.net mvc 中找不到允许最多 2 位数字的 [RegularExpression],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37265266/