yohan.jayarathna yohan.jayarathna - 3 months ago 17
Javascript Question

Angular custom directive for positive integers

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

Answer
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/