Skip to main content

AngularJs allow only numbers, numeric input in textbox

In this article, I am sharing code sample for allow only numbers and numeric input in textbox.

The example for allow only numbers in text-box as following -

HTML code looks like -
<input type="text" name="phoneNumber" only-digits ng-required="true" ng-minlength="10" ng-maxlength="11">

AngularJs code looks like -
var app = angular.module("myApp", []);

//This directive allow numbers only in the input textbox, just type 1234567890
app.directive('digitsOnly', allowOnlyNumbers);

//This directive allow numbers, numeric in the input textbox, just type 1234567890 or 1234567890.23
app.directive('onlyDigits', allowOnlyNumberNumeric);

//This method allow numbers only in the input textbox, just type 1234567890
var allowOnlyNumbers = 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);
        }
    };
}

//This method allow numbers, numeric in the input textbox, just type 1234567890 or 1234567890.23
var allowOnlyNumberNumeric = 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);
        }
    };
}