Directive to Allow Only Numbers Using AngularJs

Introduction

Before reading this article there is only one prerequisite condition; you should know how to create a directive in AngularJs and why we need to create them.

Step 1

First of all you need to add AngularJs and jQuery to your page, just like here:

<head runat="server">  
    <title></title>  
    <script src="angular.min.js"></script>  
    <script src="jquery-1.11.1.min.js"></script>  
</head>

You can either download them from my code that is available at the start of this article or you can download from their official websites.

(AngularJs file can be downloaded from here also).

Step 2

Now I am just adding a textbox where I need to allow only numbers using an AngularJs directive.

<body>  
    <form ng-app="app" id="form1" runat="server">  
        <div>
            <h3> Demo to Allow Numbers Only </h3>
            <hr />  
            Provide Your Mobile Number: <input type="text"  
                name="MobileNumber"  
                class="form-control"  
                allow-only-numbers />  
            <hr />  
        </div>  
    </form>  
</body>

Step 3

Now we need to work on the Angular code, the main part of this article.

<script>  
        var app = angular.module('app', []);  
        app.directive('allowOnlyNumbers', function () {  
            return {  
                restrict: 'A',  
                link: function (scope, elm, attrs, ctrl) {  
                    elm.on('keydown', function (event) {  
                        if (event.which == 64 || event.which == 16) {  
                            // to allow numbers  
                            return false;  
                        } else if (event.which >= 48 && event.which <= 57) {  
                            // to allow numbers  
                            return true;  
                        } else if (event.which >= 96 && event.which <= 105) {  
                            // to allow numpad number  
                            return true;  
                        } else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {  
                            // to allow backspace, enter, escape, arrows  
                            return true;  
                        } else {  
                            event.preventDefault();  
                            // to stop others  
                            return false;  
                        }  
                    });  
                }  
            }  
        });  
</script>

Here I first created a module named "app". The module creation is a necessary part if you want to use Angular. This module is added to the HTML page using the ng-app directive.

Then I created the directive with the name "allowOnlyNumbers". If you are creating any kind of directive using AngularJs then you must always check that the name is provided using "-" in your HTML page and these dashes "-" will be replaced by capital letters in the Angular code.

Since I had applied this directive to the attribute of the textbox I had restricted this directive using "A" for Attribute.

I had applied this directive on the keydown event of the textbox.

After those various conditions are applied to the ASCII values of the keys to allow or to stop them. In any case our ASCII values are not allowed. event.preventDefault() will remove that character and will revert to the previous value.

But still I had the serious problem of all the characters that were entered by pressing the shift + key were not removed by this code, so I used simple jQuery at the start of the code to help prevent this situation.

var $input = $(this);  
var value = $input.val();  
value = value.replace(/[^0-9]/g, '')  
$input.val(value);

So now our directive looks as in:​​​​​​​

app.directive('allowOnlyNumbers', 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, '')  
                $input.val(value);  
                if (event.which == 64 || event.which == 16) {  
                    // to allow numbers  
                    return false;  
                } else if (event.which >= 48 && event.which <= 57) {  
                    // to allow numbers  
                    return true;  
                } else if (event.which >= 96 && event.which <= 105) {  
                    // to allow numpad number  
                    return true;  
                } else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {  
                    // to allow backspace, enter, escape, arrows  
                    return true;  
                } else {  
                    event.preventDefault();  
                    // to stop others  
                    //alert("Sorry Only Numbers Allowed");  
                    return false;  
                }  
            });  
        }  
    }  
});

Output

Now our application is created and we can check the output.

On running the application a simple textbox will be shown where only numbers are allowed.

Directive in AngularJS

If you press the numbers from anywhere in the key, they will be allowed but all the other characters will not be allowed to exist, even if they are special characters.

Directive in AngularJS

In my next article, you can read How to Allow Decimal Numbers With Only a Single Decimal Point (.) Using AngularJs Directive.


Similar Articles