正則表示式--限制input輸入0~1之間的小數,含0,1,最多兩位小數
阿新 • • 發佈:2019-02-03
一個簡單的正則表示式,工作中可能經常用到,限制字串的輸入、數字的輸入,這些用一個onkeyup就解決了,如:onkeyup="value=value.replace(/[^\d]/g,'') //限制輸入數字
最近有個小需求,限制輸入框輸入費率,要求:只能輸入0-1之間的小數,最大是1,最小為0,且最多輸入2位小數
正則表示式:angular中定義一個ng-keyup="restrictInp()",寫法如下,這樣就可以限制了,input屬性中加了限制maxlength=4,這樣的話能保證最多輸入2位小數
$scope.restrictInp = function(input) { var reg = /^(0.\d+|0|1)$/; if (reg.test(input)) { $scope.deptExpressFeeVo.configValue = input; } else { if (input != "0.") $scope.deptExpressFeeVo.configValue = ""; } };
之前把正則表示式放到input輸入框中直接限制,一直有問題:如下(注意:該方法不可行)
<input type="text" onkeyup="value=value.replace(/^(0.\d+|0|1)$/,'')" maxlength="4"
ng-model="deptExpressFeeVo.configValue" />
但平時限制只輸入數字的時候還是可以直接寫在輸入框的:
<input type="text" onkeyup="value=value.replace(/[^\d]/g,'')" maxlength="4" ng-model="deptExpressFeeVo.configValue" />