Monday, January 14, 2019

Allow only numbers/decimal in input box using AngularJS

If your requirement is to restrict the user input on number and decimal using angularJS then this post will help you in that. If you are using the jQuery then you can visit this post.
Let’s get started
Step 1 – Prerequisites
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.9/angular.js
Step 2 – HTML Code
<input name="NoOfContracts" allow-Decimal-Numbers type="text" id="NoOfContracts" />
<input name="Price" allow-Numbers type="text" id="Price" />

Step 3 – angularJS code
Only Numeric
                var app = angular.module('App', []);
       app.directive('allowNumbers'function () {
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                element.bind('input'function () {
                    var position = this.selectionStart - 1;

                    //remove all but number
                    var fixed = this.value.replace(/[^0-9]/g'');

                    if (this.value !== fixed) {
                        this.value = fixed;
                        this.selectionStart = position;
                        this.selectionEnd = position;
                    }
                });
            }
        }
    });
Decimal
    app.directive('allowDecimalNumbers'function () {
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                element.bind('input'function () {
                    var position = this.selectionStart - 1;

                    //remove all but number and .
                    var fixed = this.value.replace(/[^0-9\.]/g'');
                    if (fixed.charAt(0) === '.')                  //can't start with .
                        fixed = fixed.slice(1);

                    var pos = fixed.indexOf(".") + 1;
                    if (pos >= 0)               //avoid more than one .
                        fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.''');

                    if (this.value !== fixed) {
                        this.value = fixed;
                        this.selectionStart = position;
                        this.selectionEnd = position;
                    }
                });
            }
        }
    });

No comments: