2015-10-15 38 views
1

我正在使用表單驗證並希望使用模式屬性來驗證輸入字段。該字段具有以下標準:html5模式匹配浮點數和/或百分比

  1. 它必須是一個數(整數或浮點數)
  2. 可以允許至多2個小數點(例如:100.24)
  3. 只有一個點被允許(例如:100.25 0.35是無效的)
  4. 可以用百分比(%)簽署最終(但並不總是必要的)

那麼應該是什麼的確切模式RegEx。我想用下面的代碼,但如何實現百分比條件?

<input type="text" 
     pattern="[0-9]+([\.][0-9]{0,2})?" 
     title="This must be a number with up to 2 decimal places and/or %"> 

回答

3

你快到了。添加%?到您的模式:

input:invalid { 
 
    color: red; 
 
}
<input type="text" 
 
     pattern="[0-9]+(\.[0-9]{0,2})?%?" 
 
     title="This must be a number with up to 2 decimal places and/or %">

+0

未能在1% 你可以爲這種情況下更新? –