0
我正在寫一個角度指令,它只允許用戶在範圍內的輸入字段中輸入數字。不允許兩個或更多零的正則表達式在自定義角度指令的開始
HTML代碼
<input non-negative-number range-min="1" range-max="5000" ng-model="number1">
<input non-negative-number range-min="0" range-max="1000" ng-model="number2">
角指令
angular.module("NumberDirective", [])
.directive('nonNegativeNumber', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, ngModel) {
var lastVal = null;
if (!ngModel) { return; }
ngModel.$parsers.push(function(val) {
lastVal = ngModel.$modelValue;
var pattern = /[^0-9]+/g;
var parsed = val.replace(pattern, '');
if (parseInt(parsed) > parseInt(attrs.rangeMax)) { parsed = lastVal; }
if (parseInt(parsed) < parseInt(attrs.rangeMin)) { parsed = lastVal; }
if (val !== parsed) {
lastVal = parsed;
ngModel.$setViewValue(parsed);
ngModel.$render();
}
return parsed;
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
這是工作正常,但我也需要有正則表達式,必須不能讓打字兩個零的在輸入的開始,
like 00,0000000000045,00000000000000000000000100
任何人都可以提出正確的正則表達式?
謝謝,我使用這樣 變種圖案=/^ [0] {0,1} [1-9] \ d + /; 但它仍然允許儘可能多的0,因爲我想這是錯誤的在我的情況下 – zubairm
你想允許一個零和不超過一個。如果我錯了,請糾正我。 – fossil
我想用戶應該只能在01,02等數字的開始處輸入一個零,但不能爲001,00000001. 有效輸入: 1,0.01,099,99等 無效輸入: 001,0001 ,000099等等 – zubairm