0

I have the following input of type number:

<input class="number text-center" type="number" step="1"
       ng-model="item.formattedQuantity"
       ng-disabled="item.discount === '100.00'"
       ng-change="change(item)"
       ng-blur="blur(item)" min="0" />

What can I do to forbid users adding decimal values? I tried adding step=0.01 and ng-pattern="/^[0-9]+$/" but users could still place values like 1.5, 31.56, etc.

What can I do?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
shAkur
  • 944
  • 2
  • 21
  • 45
  • Have you checked this ? https://stackoverflow.com/questions/34013311/text-input-allow-only-integer-input-in-angularjs – sam_dev Nov 22 '19 at 13:23

1 Answers1

0

You need to create a directive to achieve that.

app.directive('numericInput', function () {
    return  {
        restrict: 'A',
        link: function (scope, elm, attrs, ctrl) {
            elm.on('input', function (event) {
                var regex = RegExp('^[0-9]+$');
                if(regex.test(event.target.value)){
                    event.preventDefault(); 
                    return true;
                else {
                    event.preventDefault(); return false;
                }
            });
        }
    }
});

Or you can try the angularjs style (found codepen here)

app.directive('numericInput', 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);
        }
    };
});

Then in your html

<input numeric-input class="number text-center" type="number" step="1"
       ng-model="item.formattedQuantity"
       ng-disabled="item.discount === '100.00'"
       ng-change="change(item)" ng-blur="blur(item)" min="0" />
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61