I'm running into an interesting problem while trying to restrict user input to a number.
在试图限制用户输入到一个数字时,我遇到了一个有趣的问题。
My HTML looks like so:
我的HTML看起来是这样的:
<input name="activeDate" type="number" class="form-control" ng-model="account.tag.activeDate"></input>
...and my relevant Angular controller code like so(this is inside a click handler):
…我的相关角控制器代码如下(这是一个点击处理器)
tag.activeDate = moment.utc().add(tag.activeDate, tag.tagDurationType).toISOString();
Unfortunately when I click the button which submits my form and calls that click handler I get this error in my console:
不幸的是,当我单击提交表单的按钮并调用单击处理程序时,我在我的控制台中会得到这个错误:
[ngModel:numfmt] Expected `2015-08-27T22:09:18.919Z` to be a number
Looks like my input is checked upon submitting, when it's converted to a date within my controller. How do I limit user input to numbers without running into this?
看起来我的输入在提交时被检查,当它在我的控制器中被转换为日期时。如何将用户输入限制为数字而不涉及到这个?
2 个解决方案
#1
2
Use ng-pattern="/^(\d)+$/"
- it's simple regex expression
使用ng-pattern = " / ^(\ d)+ /美元”——这是简单的正则表达式
var app = angular.module('num', []);
app.controller('numCtrl', function($scope, $http){
$scope.digits = {};
});
angular.bootstrap(document.body, ['num']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="numCtrl">
<form class="digits" name="digits" ng-submit="getGrades()" novalidate >
<input type="text" placeholder="digits here plz" name="nums" ng-model="nums" required ng-pattern="/^(\d)+$/" />
<p class="alert" ng-show="digits.nums.$error.pattern">Numbers only, please.</p>
<br>
<input class="btn" type="submit" value="Do it!" ng-disabled="!digits.$valid" />
</form>
</body>
#2
0
Select your input element, then do the following you have to look up value of number0Key and number9Key:
选择您的输入元素,然后执行以下操作,您必须查找number0Key和number9Key的值:
myElement.on("keypress", function(e) {
if (e.which < number0Key || e.which > number9Key) {
e.stopPropagation();
}
});
#1
2
Use ng-pattern="/^(\d)+$/"
- it's simple regex expression
使用ng-pattern = " / ^(\ d)+ /美元”——这是简单的正则表达式
var app = angular.module('num', []);
app.controller('numCtrl', function($scope, $http){
$scope.digits = {};
});
angular.bootstrap(document.body, ['num']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="numCtrl">
<form class="digits" name="digits" ng-submit="getGrades()" novalidate >
<input type="text" placeholder="digits here plz" name="nums" ng-model="nums" required ng-pattern="/^(\d)+$/" />
<p class="alert" ng-show="digits.nums.$error.pattern">Numbers only, please.</p>
<br>
<input class="btn" type="submit" value="Do it!" ng-disabled="!digits.$valid" />
</form>
</body>
#2
0
Select your input element, then do the following you have to look up value of number0Key and number9Key:
选择您的输入元素,然后执行以下操作,您必须查找number0Key和number9Key的值:
myElement.on("keypress", function(e) {
if (e.which < number0Key || e.which > number9Key) {
e.stopPropagation();
}
});