2016-05-17 41 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 ..你明白我的觀點了嗎? –