[英]Angular Directive for input Numbers only
I am creating a directive
to restrict input box to accept numbers only. 我正在创建一个
directive
以限制输入框仅接受数字。 It should accept 1-9999999999, but no leading 0. It is working but after entering first number it is accepting all numbers and characters. 它应该接受1-9999999999,但不能以0开头。它可以工作,但是输入第一个数字后,它可以接受所有数字和字符。 Please help me to resolve this.it should accept 10, but not 01. For this my code is,
请帮助我解决此问题。它应该接受10,但不能接受01。为此,我的代码是,
HTML: HTML:
<input type="text" ng-model="number" required="required" numbers-only="numbers-only" />
JS: JS:
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/^[^1-9]*/g, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
function MyCtrl($scope) {
$scope.number = ''
}
Just add an alternative ^0+
to /[^0-9]+/g
so that the leading zeros could be removed: 只需在
/[^0-9]+/g
添加一个替代^0+
即可删除前导零:
var transformedInput = inputValue.replace(/^0+|[^0-9]+/g, '');
// ^^^
See updated fiddle . 参见更新的小提琴 。
The ^0+
matches 1 or more ( +
) zeros that are at the string start ( ^
). ^0+
与字符串开头( ^
)处的1个或多个( +
)零匹配。
I have found this working fiddle (not created by me). 我找到了这个工作的小提琴 (不是我创造的)。 Hope this helps.
希望这可以帮助。
Directive: 指示:
fessmodule.directive('format', ['$filter', function ($filter) {
return {
require: '?ngModel',
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.unshift(function (a) {
return $filter(attrs.format)(ctrl.$modelValue)
});
ctrl.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
elem.val($filter(attrs.format)(plainNumber));
return plainNumber;
});
}
};
}]);
PS I have not tested. PS我还没有测试。
well you just need to remove the first ^
from your pattern. 好吧,您只需要从模式中删除第一个
^
。 here is updated fiddle 这是更新的小提琴
use this - 用这个 -
replace(/[^1-9]*/g, '');
you can use the below one to restrict 0 at beginning updated fiddle - 您可以在开始更新小提琴时使用下面的一个来限制0-
replace(/^0|[^0-9]/, '');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.