AngularJS directive to allow number only in textbox

Standard

Here I show how to use AngularJS directive to allow only numbers to be entered in a textbox. This is useful for phone numbers, IDs, ZipCodes, and, well, that’s about it.

Demo on Github

app.directive('numbersOnly', function () {
        return {
            require: 'ngModel',
            link: function (scope, element, attr, ngModelCtrl) {
                function fromUser(text) {
                    if (text) {
                        var transformedInput = text.replace(/[^0-9-]/g, '');
                        if (transformedInput !== text) {
                            ngModelCtrl.$setViewValue(transformedInput);
                            ngModelCtrl.$render();
                        }
                        return transformedInput;
                    }
                    return undefined;
                }
                ngModelCtrl.$parsers.push(fromUser);
            }
        };
    });

<input type="text" name="txtAccountNumber" numbers-only ng-model="account">

Update:

I have tested on chrome/firefox/IE 9+, It is working fine,  It doesn’t allow space even.
For all those have issues like not working in specific browser or space(‘ ‘) character is allowed etc, please make sure there are no integration issues by inspecting browser console window.
P.S. ng-model attribute is required to use that directive
<input type="text" name="txtAccountNumber" numbers-only ng-model="account">

9 thoughts on “AngularJS directive to allow number only in textbox

    • I have tested on chrome/firefox/IE 9+, It is working fine, It doesn’t allow space even.
      For all those newbies, please make sure there are no integration issues by inspecting browser console window.🙂
      P.S. ng-model attribute is required to use that directive

      Like

  1. I have tested on chrome/firefox/IE 9+, It is working fine, It doesn’t allow space even.
    For all those newbies, please make sure there are no integration issues by inspecting browser console window. 🙂
    P.S. ng-model attribute is required to use that directive

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s