我在html文件中输入以下内容:
<input name="password"
id="newPasswordConfirmation"
ng-model="newPasswordConfirmation"
type="number"
inputmode="numeric"
placeholder=""
required
minlength="8"
maxlength="8"
autocomplete="off"
ng-maxlength="8"
autocorrect="off"
autocapitalize="off"
style="-webkit-text-security: disc; text-security: disc;">
我想将输入限制为8种算法,但是当我在移动设备(android)上键入内容时,我可以继续输入8种算法。为什么这不起作用?您如何进行此限制?
答案 0 :(得分:1)
如注释中所述,maxlength
不适用于数字输入。来自MDN:
最大长度:如果type属性的值为文本,电子邮件,搜索,密码, tel或url,此属性指定最大字符数 (用户可以输入UTF-16代码单位)。对于其他控制 类型,将被忽略。
这是一个小指令,您可以改用它:
angular.module('myApp').directive('maxLength', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var maxLength = attrs.maxLength || false;
if (maxLength) element.on('keydown keypress keyup paste propertychange', function(e) {
if (element[0].value.length >= maxLength - 1) {
element[0].value = element[0].value.slice(0, maxLength)
}
})
}
}
});
<input type="number" max-length="8">
答案 1 :(得分:0)
<div ng-app="App" ng-controller="Ctrl">
<input type="text"
ng-model="model"
ng-keypress="limitKeypress($event, model, 8)"
placeholder="enter first 8 digits">
</div>
angular.module('App', []).controller('Ctrl', Ctrl);
function Ctrl($scope) {
$scope.model = 'test'
$scope.limitKeypress = function ($event, value, maxLength) {
if (value != undefined && value.toString().length >= maxLength) {
$event.preventDefault();
}
}
}
Ctrl.$inject = ['$scope'];