Restrict user from entering non-numeric inputs using a directive in Angular.

There must a requirement in any application to allow only entering numbers in text inputs. This can be solved by creating a directive with onKeydown event handler. And then adding this directive to input element. See below code sample.

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[allowNumbersOnly]'
})

export class AllowNumbersOnlyDirective {

  constructor() {}

  /**
   * On keydown event handler.
   * Here we check if the input is number or not, if not we just ignore the input.
   * @param {KeyboardEvent} $event
   * @return {boolean}
   */
  @HostListener('keydown', ['$event'])
  onKeydown($event: KeyboardEvent) {
    if (!$event) {
      return true;
    }
    return ($event.keyCode > 95 && $event.keyCode < 106)
        || ($event.keyCode > 47 && $event.keyCode < 58)
        || ($event.keyCode > 36 && $event.keyCode < 41)
        || $event.keyCode === 8;

  }
}

We add this directive to input element like below.

<input type="text" allowNumbersOnly class="form-control">

When user tries to enter value other than number we simple ignore the input.

Also don’t forget to add the directive AllowNumbersOnlyDirective to the module declarations.

Few reads:

Published by Kumar Gandhi K

Hi! I’m Kumar and I live in Bangalore (IN) with my family. By profession I’m a Web Developer experienced in a vast variety of frameworks and technologies, like, HTML, CSS, JavaScript, Angular, Bootstrap… Using these i have built or sometimes maintained mid market and enterprise level applications. I worked for few software companies over the years and on few domains like finance, field-service and storage. I also did consulting job at one point. I am loyal and hard (or for better word smart) working individual. In my free time I read books, in fact I buy a lot of books hoping that some day I might find all the time in the world to read them and I also enjoy watching TV.

Leave a comment