2016-05-17 45 views
2

我在一个asp.net MVC Web应用程序工作的一个[正则表达式]我的asp.net mvc的内允许最大值和我有与SQL Server Decimal(19,2)内的以下数据类型的小数场。现在我想做一个检查,用户只能输入2位数字,但他们可以添加数字,如10,20(没有任何数字)..但如果他们设置数字来检查,有最多两位数字。找不到的2位

现在我尝试以下正则表达式,但他们没有行之有效: -

这正则表达式将不会允许用户输入不包含数字的数字: -

[RegularExpression(@"^\d+.\d{0,2}$", ErrorMessage = "Value can't have more than 2 decimal places")] 
public Nullable<decimal> CostPrice { get; set; } 

,这正则表达式,,将引发一个错误,如果用户尝试输入数字: -

[RegularExpression(@"^(\d{0,2})$", ErrorMessage = "error Message")] 
public Nullable<decimal> CostPrice { get; set; } 

因此,谁能书于什么是最好的正则表达式,即强制用户输入最多2位数字,同时允许他们输入没有任何数字的数字?

+0

按数字做y ou表示小数位吗? – etoisarobot

+0

@DoNothing是完全相同小数 –

回答

0

说明

^(?!\s*[0-9]{0,2}\s*$).*$ 

Regular expression visualization

这个正则表达式将执行以下操作:

  • 验证该字符串最多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 
---------------------------------------------------------------------- 
+0

但你的例子<< ^(?!\ S * [0-9] {0,2} \ S * $)。* $ >>是没有关系的,我的问题是什么我寻找因为是接受至多2位小数,所以这些在我的情况下应该是有效的10或10.1或1.23 ..但是这些不应该是有效的10.123或11.2345 ..你明白我的观点了吗? –