首页 > 解决方案 > maxlenght 或 ng-maxlength 似乎都不起作用

问题描述

我的 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 个 algarisms,但是当我在移动设备 (android) 上输入时,我可以继续输入 8 个 algarisms。为什么这不起作用,你怎么能做出这个限制?

标签: javascripthtmlangularjs

解决方案


如评论中所述,maxlength不适用于数字输入。来自MDN

maxlength:如果 type 属性的值为 text、email、search、password、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">

推荐阅读