我正在编写一个角度指令,它只允许用户在范围内的输入字段中输入数字。
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();
}
});
}
};
});
这工作正常,但我还需要正则表达式,不能在输入的开头键入两个零,
<00>如00,0000000000045,00000000000000000000000100任何人都可以建议正确的正则表达式吗?
答案 0 :(得分:0)
尝试
^[0]{0,1}[1-9]\d{0,}
^ asserts position at start of the string
Match a single character present in the list below [0]{0,1}
{0,1} Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
0 matches the character 0 literally (case sensitive)
Match a single character present in the list below [1-9]
1-9 a single character in the range between 1 (ASCII 49) and 9 (ASCII 57) (case sensitive)
\d{0,} matches a digit (equal to [0-9])
{0,} Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Global pattern flags
g modifier: global. All matches (don't return after first match)