1

I have text field in my application which should accept only positive integers only.(no decimal, no negatives). Basically I want to restrict the user to enter only between 1 to 9999 only.

<input type="text" min="0" max="99" number-mask="">

I found this from googling jsfiddle it accepts negative integers and it doesn't work with internet explorer.

I don't have mush experience writing directives. At the moment I am learning angular as well. (I use typscript to generate angular in my .net mvc project)

var app = angular.module('myApp', []);

app.directive('numberMask', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).numeric();
        }
    }
});

In this code is it possible to check for negatives? Something like

if(element <0 && element.lenth > 4)
  .....
else
  ....

Thanks in Advance

yohan.jayarathna
  • 3,423
  • 13
  • 56
  • 74

2 Answers2

4
angular.module('myapp', [])
.directive('numberMask', function() {
    return function(scope, element, attrs) {
        var min = parseInt(attrs.min, 10) || 0,
            max = parseInt(attrs.max, 10) || 10, 
            value = element.val();
        element.on('keyup', function(e) {
            if (!between(element.val(), min, max)) {
               element.val(value);
            } else {
                value = element.val();
            }
        });

        function between(n, min, max) { return n >= min && n <= max; }
    }
});

http://jsfiddle.net/9HgBY/

Adrian
  • 190
  • 6
1

I modified Adrians answer to support use of ng-model. It most probably isn't the prettiest piece of code, but it gets the job done.

angular.module('myapp', [])
.directive('numberMask', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, elem, attrs, ctrl) {   
            var oldValue = null;
            scope.$watch(attrs.ngModel, function (newVal, oldVal) {
                var min = parseInt(attrs.min) || 0;
                var max = parseInt(attrs.max) || 10;
                if (!between(newVal, min, max)) {
                    if (newVal > max)
                        ctrl.$setViewValue(max);
                    else if (newVal < min)
                        ctrl.$setViewValue(min);
                    else
                        ctrl.$setViewValue(oldValue);
                    ctrl.$render();
                }else{
                    oldValue = newVal;
                }
            }, true);

            function between(n, min, max) { return n >= min && n <= max; }
        }
    };
});

Here's Adrians fiddle with my additions http://jsfiddle.net/9HgBY/3/

Nikolaj Dam Larsen
  • 5,455
  • 4
  • 32
  • 45