Javascript 角度1:输入字段应仅允许数字
输入字段应仅允许0-9之间的数字,如果不是数字,则输入的值甚至不应显示在字段中。我已经尝试使用使用$parsers的指令来实现这一点Javascript 角度1:输入字段应仅允许数字,javascript,angularjs,regex,Javascript,Angularjs,Regex,输入字段应仅允许0-9之间的数字,如果不是数字,则输入的值甚至不应显示在字段中。我已经尝试使用使用$parsers的指令来实现这一点 app.directive('onlyNumber', function() { return { require: 'ngModel', restrict: 'A', link: function(scope, element, attrs, modelCtrl) { modelCtrl.$parsers.push(function(inp
app.directive('onlyNumber', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue == null)
return ''
cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
}))
这允许使用字符,并且只限制特殊字符,我希望限制除数字以外的任何字符 您可以替换正则表达式,这样它只允许数字。 尝试使用
/\D/gi
要了解更多详细信息,您可以阅读有关正则表达式的内容
您可以尝试使用下面的代码将其限制为仅包含数字字符
app.directive('onlyNumber', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, modelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9-]/g, '');
if (transformedInput !== text) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
}
return undefined;
}
modelCtrl.$parsers.push(fromUser);
}
};
});
Regex:
^\b[0-9]+\b
或^[0-9]+$
或^\d+$
var input1='8547'
变量输入2='fasd55dasd 884'
console.log(/^\b[0-9]+\b/.test(input1),/^[0-9]+$/.test(input2))代码>可能重复的