在 AngularJS 中,是否有任何可用功能只允许在文本框中输入数字like
此代码显示了如何防止输入非数字符号的示例。
angular.module('app').
directive('onlyDigits', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return '';
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput !== inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
HTML
<input type="text" name="number" only-digits>
//只需输入123
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9]/g, '');
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits,10);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
// 输入:123 或 123.45
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
我刚刚在指令中使用了 ng-keypress 进行输入。
HTML:
<input type="text" ng-keypress="filterValue($event)"/>
JS:
$scope.filterValue = function($event){
if(isNaN(String.fromCharCode($event.keyCode))){
$event.preventDefault();
}
};
此功能正是您所需要的。 http://docs.angularjs.org/api/ng.directive:input.number
编辑:
您可以将 jquery 插件包装到指令中。我在这里创建了一个示例:http://jsfiddle.net/anazimok/jTJCF/
HTML:
<div ng-app="myApp">
<div>
<input type="text" min="0" max="99" number-mask="" ng-model="message">
<button ng-click="handleClick()">Broadcast</button>
</div>
</div>
CSS:
.ng-invalid {
border: 1px solid red;
}
JS:
// declare a module
var app = angular.module('myApp', []);
app.directive('numberMask', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).numeric();
}
}
});
这是最简单、最快的方法,只允许输入数字。
<input type="text" id="cardno" placeholder="Enter a Number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' required>
以安东的答案为基础——
angular.module("app").directive("onlyDigits", function ()
{
return {
restrict: 'EA',
require: '?ngModel',
scope:{
allowDecimal: '@',
allowNegative: '@',
minNum: '@',
maxNum: '@'
},
link: function (scope, element, attrs, ngModel)
{
if (!ngModel) return;
ngModel.$parsers.unshift(function (inputValue)
{
var decimalFound = false;
var digits = inputValue.split('').filter(function (s,i)
{
var b = (!isNaN(s) && s != ' ');
if (!b && attrs.allowDecimal && attrs.allowDecimal == "true")
{
if (s == "." && decimalFound == false)
{
decimalFound = true;
b = true;
}
}
if (!b && attrs.allowNegative && attrs.allowNegative == "true")
{
b = (s == '-' && i == 0);
}
return b;
}).join('');
if (attrs.maxNum && !isNaN(attrs.maxNum) && parseFloat(digits) > parseFloat(attrs.maxNum))
{
digits = attrs.maxNum;
}
if (attrs.minNum && !isNaN(attrs.minNum) && parseFloat(digits) < parseFloat(attrs.minNum))
{
digits = attrs.minNum;
}
ngModel.$viewValue = digits;
ngModel.$render();
return digits;
});
}
};
});
我的解决方案接受复制和粘贴并保存插入符的位置。它用于产品成本,因此仅允许正小数值。可以很容易地重构以允许负数或仅允许整数。
angular
.module("client")
.directive("onlyNumber", function () {
return {
restrict: "A",
link: function (scope, element, attr) {
element.bind('input', function () {
var position = this.selectionStart - 1;
//remove all but number and .
var fixed = this.value.replace(/[^0-9\.]/g, '');
if (fixed.charAt(0) === '.') //can't start with .
fixed = fixed.slice(1);
var pos = fixed.indexOf(".") + 1;
if (pos >= 0) //avoid more than one .
fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');
if (this.value !== fixed) {
this.value = fixed;
this.selectionStart = position;
this.selectionEnd = position;
}
});
}
};
});
放入html页面:
<input type="text" class="form-control" only-number ng-model="vm.cost" />
这就是对我有用的方法。它基于 samnau anwser,但允许使用
ENTER
提交表单,使用 UP
和 DOWN
箭头增加和减少数量,使用 DEL
、BACKSPACE
、LEFT
和 RIGHT
进行编辑,并导航槽带有 TAB
的字段。请注意,它适用于正整数,例如金额。
HTML:
<input ng-keypress="onlyNumbers($event)" min="0" type="number" step="1" ng-pattern="/^[0-9]{1,8}$/" ng-model="... >
角度:
$scope.onlyNumbers = function(event){
var keys={
'up': 38,'right':39,'down':40,'left':37,
'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
'0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
};
for(var index in keys) {
if (!keys.hasOwnProperty(index)) continue;
if (event.charCode==keys[index]||event.keyCode==keys[index]) {
return; //default event
}
}
event.preventDefault();
};
基于 djsiz 解决方案,包装在指令中。 注意:它不会处理数字,但可以轻松更新
angular
.module("app")
.directive("mwInputRestrict", [
function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
element.on("keypress", function (event) {
if (attrs.mwInputRestrict === "onlynumbers") {
// allow only digits to be entered, or backspace and delete keys to be pressed
return (event.charCode >= 48 && event.charCode <= 57) ||
(event.keyCode === 8 || event.keyCode === 46);
}
return true;
});
}
}
}
]);
HTML
<input type="text"
class="form-control"
id="inputHeight"
name="inputHeight"
placeholder="Height"
mw-input-restrict="onlynumbers"
ng-model="ctbtVm.dto.height">
只需使用 HTML5
<input type="number" min="0"/>
您可以检查一下 https://github.com/rajesh38/ng-only-number
你可以这样做: 将 ng-pattern 与正则表达式“/^[0-9]+$/”一起使用,这意味着只有整数才有效。
<form novalidate name="form">
<input type="text" data-ng-model="age" id="age" name="age" ng-pattern="/^[0-9]+$/">
<span ng-show="form.age.$error.pattern">The value is not a valid integer</span>
</form>
此解决方案仅接受数字“.”和“-”
这也限制了文本框中的空格输入。我已经使用该指令来实现相同的目的。
请在下面的工作示例中找到解决方案。
http://jsfiddle.net/vfsHX/2697/
HTML:
<form ng-app="myapp" name="myform" novalidate>
<div ng-controller="Ctrl">
<input name="number" is-number ng-model="wks.number">
<span ng-show="!wks.validity">Value is invalid</span>
</div>
JS:
var $scope;
var app = angular.module('myapp', []);
app.controller('Ctrl', function($scope) {
$scope.wks = {number: 1, validity: true}
});
app.directive('isNumber', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.bind("keydown keypress", function (event) {
if(event.which === 32) {
event.returnValue = false;
return false;
}
});
scope.$watch(attrs.ngModel, function(newValue,oldValue) {
var arr = String(newValue).split("");
if (arr.length === 0) return;
if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
if (arr.length === 2 && newValue === '-.') return;
if (isNaN(newValue)) {
//scope.wks.number = oldValue;
ngModel.$setViewValue(oldValue);
ngModel.$render();
}
});
}
};
});
简单易懂。 只需复制粘贴此代码,您的问题就会得到解决。对于更多条件,只需更改模式中的值。您的工作就会完成。
<input type="text" pattern="[0-9]{0,}" oninvalid="this.setCustomValidity('Please enter only numeric value. Special character are not allowed.')" oninput="setCustomValidity('')">
这个答案是对 Leopoldo 的答案的简化和优化。
每次按键时都会根据您的输入触发一个功能,如下所示:
<input type="text" ng-keydown="onlyNumbers($event);"/>
您可以在控制器中以这种方式描述功能
$scope.onlyNumbers = function(event){
// 'up': 38,'right':39,'down':40,'left':37,
// 'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
// '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
var keys = { 38:true,39:true,40:true,37:true,27:true,8:true,9:true,13:true,
46:true,48:true,49:true, 50:true,51:true,52:true,53:true,
54:true,55:true,56:true,57:true };
// if the pressed key is not listed, do not perform any action
if(!keys[event.keyCode]) { event.preventDefault(); }
}
如果您使用 Angular 2+,您可以通过以下方式调用相同的函数:
<input type="text" (keydown)="onlyNumbers($event);"/>
您的 Angular 2+ 函数应该如下所示:
onlyNumbers(event) { // the logic here }
我遇到了类似的问题,最终陷入了钩子和事件
ng-change="changeCount()"
然后:
self.changeCount = function () {
if (!self.info.itemcount) {
self.info.itemcount = 1;
}
};
因此,如果插入无效号码,则用户默认为1。
我将 jQuery 安排在 this
.directive('numbersCommaOnly', function(){
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.on('keydown', function(event) {
// Allow: backspace, delete, tab, escape, enter and .
var array2 = [46, 8, 9, 27, 13, 110, 190]
if (array2.indexOf(event.which) !== -1 ||
// Allow: Ctrl+A
(event.which == 65 && event.ctrlKey === true) ||
// Allow: Ctrl+C
(event.which == 67 && event.ctrlKey === true) ||
// Allow: Ctrl+X
(event.which == 88 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.which >= 35 && event.which <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((event.shiftKey || (event.which < 48 || event.which > 57)) && (event.which < 96 || event.which > 105)) {
event.preventDefault();
}
});
}
};
})
<input type="text" ng-keypress="checkNumeric($event)"/>
//inside controller
$scope.dot = false
$scope.checkNumeric = function($event){
if(String.fromCharCode($event.keyCode) == "." && !$scope.dot){
$scope.dot = true
}
else if( isNaN(String.fromCharCode($event.keyCode))){
$event.preventDefault();
}
我知道这是一篇旧帖子,但是对My Mai的答案的改编对我来说效果很好......
angular.module("app").directive("numbersOnly", function() {
return {
require: "ngModel",
restrict: "A",
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
//transform val to a string so replace works
var myVal = val.toString();
//replace any non numeric characters with nothing
var digits = myVal.replace(/\D/g, "");
//if anything needs replacing - do it!
if (digits !== myVal) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
我已经完成了
.js
$scope.numberOnly="(^[0-9]+$)";
.html
<input type="text" name="rollNo" ng-model="stud.rollNo" ng-pattern="numberOnly" ng-maxlength="10" maxlength="10" md-maxlength="10" ng-required="true" >
使用
ng-only-number
仅允许数字,例如:
<input type="text" ng-only-number data-max-length=5>
<input
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||
event.charCode == 0 || event.charCode == 46">