AngularJs allow only numbers

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);
        }
    };
}
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^