I am working on a directive to only allow users to input numbers. Check out my implementation below.
Snippet from my directive template:
<input type="text" maxlength="5" ng-keypress="allowNumbers($event)">
Function in my directive:
$scope.allowNumbers= function (ev) {
var key = ev.charCode || ev.keyCode || 0;
var allowed = (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
return allowed;
};
During my debugging process, I encountered an issue where the value in the textbox was still being entered even if the function returned either true
or false
. Is there a way to prevent non-number key presses from being entered?