This is my custom version of an Angular JS Directive to ensure input values are digits only.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
amodule.directive('numbersOnly', function() { return { restrict: 'A', require: '?ngModel', link: function (scope, element, attrs, ngModel) { if (!ngModel) return; ngModel.$parsers.push(function(val) { var parsed = val.replace( /[^0-9]+/g, ''); if (val !== parsed) { ngModel.$setViewValue(parsed); ngModel.$render(); } return parsed; }); } }; }); |
You can then use the directive in the input field like this:
|
1 |
<input type="text" numbers-only/> |
Using ng-pattern regex is good only for validation but does not hinder the user from inputting non-numeric characters so having a directive like this makes it even better to be sure that inputs are numeric only.