html5模式匹配浮动和/或百分比

时间:2015-10-15 07:16:32

标签: regex html5 pattern-matching

我正在使用表单验证,并希望使用模式属性来验证输入字段。该字段具有以下标准:

  1. 必须是数字(整数或浮点数)
  2. 最多允许2个小数点(例如:100.24)
  3. 只允许一个点(例如:100.25.35无效)
  4. 可能以百分号(%)结束(但并非总是必要)
  5. 那么应该是什么样的确切模式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 %">
    

1 个答案:

答案 0 :(得分:3)

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

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