输入文本字符数限制

use*_*836 4 validation input angularjs angularjs-directive angularjs-scope

我希望我的文本框只允许数字,并且也有字符限制。

目前,我的数字正在工作......现在我在弄清楚如何限制字符方面遇到问题。

这是我所拥有的...

JS:

app.directive('numbersonly', function () {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs, ctrl) {
            elm.on('keydown', function (event) {
                if (event.which == 64 || event.which == 16 && elm.val().length > 4) {
                    return false;
                } else if (event.which >= 48 && event.which <= 57) {
                    return true;
                } else if (event.which >= 96 && event.which <= 105) {
                    return true;
                } else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1 && elm.val().length > 4) {
                    return true;
                } else {
                    event.preventDefault();
                    return false;
                }
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

标记:

<input type="text" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" numbersonly required />
Run Code Online (Sandbox Code Playgroud)

kri*_*ngh 8

在html中输入属性长度。我们可以以多种形式使用它:

长度、最小长度和最大长度

尝试这个

maxlength="5"
Run Code Online (Sandbox Code Playgroud)