AngularJS directive to allow only specific numbers in input

I came across this question on stackoverflow to allow the user to type only specific numbers such as 3,6,9,12 and so on. You can use the following directive which checks for the key and allows as input.

Directive Code

 angular.module('demo').directive('restrictTo', function() {  
return {
restrict: 'A',
link: function (scope, element, attrs) {
var include = /3|6|9|12/;
element[0].addEventListener('keydown', function(event) {
if (!include.test(event.key)) {


Also we can use the ng-pattern as follows,

 input name="numberField" type="number" data-ng-model="model.number" data-ng-pattern="/^(3|6|9|12|15)$/"/>  


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.