allow only numbers

Angular Directive to Allow Decimal Numbers with a Single Dot (.)

In this example, we are determining if your input text-box already has a decimal point, if you want to prevent enter another decimals character in the same text-box.

After entered another decimal dot (.), the ASCII value will matches another entered decimal point in your text-box and remove if multiple entry .

Let's see the example -
app.directive('allowOnlyDecimalNumbers', function () {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs, ctrl) {
            elm.on('keydown', function (event) {
                var $input = $(this);
                var value = $input.val();
                value = value.replace(/[^0-9\.]/g, '')
                var findsDot = new RegExp(/\./g)
                var containsDot = value.match(findsDot)

                if (containsDot != null && ([46, 110, 190].indexOf(event.which) > -1)) {
                    event.preventDefault();

                    return false;
                }

                $input.val(value);
                if (event.which == 64 || event.which == 16) {
                    // NUMBERS 
                    return false;
                }

                if ([8, 13, 27, 37, 38, 39, 40, 110].indexOf(event.which) > -1) {
                    // BACKSPACE, ENTER, ESCAPE, AND ARROWS 
                    return true;
                }
                else if (event.which >= 48 && event.which <= 57) {
                    // NUMBERS 
                    return true;
                }
                else if (event.which >= 96 && event.which <= 105) {
                    // NUMPAD NUMBER 
                    return true;
                }
                else if ([46, 110, 190].indexOf(event.which) > -1) {
                    // DOT AND NUMPAD DOT 
                    return true;
                }
                else {
                    event.preventDefault();
                    return false;
                }
            });
        }
    }
}); 

And use this directive in your HTML –
<input type="text" name="RateOfIntrest" class="form-control" allow-only-decimal-numbers />

I hope this example will helps you.
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 Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

Angular Directive to Allow Decimal Numbers with a Single Dot (.) Angular Directive to Allow Decimal Numbers with a Single Dot (.) Reviewed by Anil Singh on 11:16 PM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^