I have a simple input number like this:
When trying to input anything other than a number or the letter \"e\
You are correct that it should be done with a directive. Simply create a directive and attach it to the input
. This directive should listen for keypress
and/or keydown
events. Possibly paste events as well. If the char entered is an 'e' or dot -- call event.preventDefault();
angular.module('app', [])
.directive('yrInteger', yrInteger);
function yrInteger() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('keypress', function(event) {
if ( !isIntegerChar() )
event.preventDefault();
function isIntegerChar() {
return /[0-9]|-/.test(
String.fromCharCode(event.which))
}
})
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<input
type="number"
yr-integer
/>
</div>
You can simply use ng-pattern
on your input
Controller
$scope.onlyDigits= /^\d+$/;
HTML
<input ng-pattern="onlyDigits" type="number" />
This pattern use \d
which is for any numeric value